Linux:ntohl无法正常工作

Kat*_*Kat 5 c++ linux endianness

我有一个需要在Windows,Linux和VxWorks上构建的项目.该项目建立在Linux和Windows上,但是为VxWorks交叉编译.要处理跨多个平台的字节序,它使用ntoh.h. Linux机器是小端,但是ntohl不会交换我的程序.

我写了一个直接包含in.h的测试程序.交换得恰到好处.我写了另一个包含ntoh.h的测试程序.交换得恰到好处.两个测试程序都链接到lib64/libc.so.6.

但是,当我编译我的项目时,ntohl不会交换.我无法使用gdb"break ntohl"命令打破ntohl.在构建时,我看到LITTLE ENDIAN警告(见下文)并且没有看到"SHOULDNT BE HERE"错误.

请帮忙.我不明白为什么会出现这个问题.

下面是ntoh.h:

#ifndef __ntoh__
#define __ntoh__

#include "basic_types.h"

#ifdef WIN32
    #include <winsock2.h>
#elif LINUX
    #include <netinet/in.h>

    //This is here to determine what __BYTE_ORDER is set to in netinet/in.h.
    // Not in original code 
    #if __BYTE_ORDER == __BIG_ENDIAN
    #warning BIG ENDIAN BYTE ORDER!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #endif 

    //This is here to determine what __BYTE_ORDER is set to in netinet/in.h. 
    // Not in original code
    #if __BYTE_ORDER == __LITTLE_ENDIAN
    #warning YAY LITTLE ENDIAN!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    #endif 
#else

  #error SHOULDNT BE HERE     //added for debugging purposes
  #define ntohl(x)        (x)
  #define ntohs(x)        (x)
  #define htonl(x)        (x)
  #define htons(x)        (x)

#endif

#endif // __ntoh__
Run Code Online (Sandbox Code Playgroud)

我的编译命令的一部分:

g++ -DDAU_PARSER -DNO_MT -DTEST_CLOCK -DLINUX  -g -Irelease/include -Irelease/include/Record_Data/ -Irelease/include/Utility -o dauParser DAU_Support_Tools/src/dau_parser.cpp DAU_Support_Tools/src/dau_parser_write_data_to_file.cpp Utility/src/Messaging/Communications/Message.cpp Utility/src/time_type.cpp Utility/src/collectable.cpp Utility/src/clist.cpp Utility/src/clock.cpp Utility/src/test_clock.cpp Utility/src/mutex.cpp Utility/src/ntoh.cpp ... 
Run Code Online (Sandbox Code Playgroud)

错误由以下行生成:

int deadbeef = 0xDEADBEEF; 
printf("TESTING DEADBEEF %x %x\n", deadbeef, ntohl(deadbeef) ); 
Run Code Online (Sandbox Code Playgroud)

这两行的输出产生相同的输出.测试DEADBEEF deadbeef deadbeef

Emp*_*ian 6

这两行的输出产生相同的输出.测试DEADBEEF deadbeef deadbeef

嗯,有些事情错的,但我们无法告诉你什么.必须调试此问题,因为您是唯一可以观察它的人.

从最简单的示例开始:

cat t.c; gcc t.c && ./a.out
#include <netinet/in.h>
#include <stdio.h>

int main() {
  int deadbeef = 0xDEADBEEF; 
  printf("TESTING DEADBEEF %x %x\n", deadbeef, ntohl(deadbeef));
  return 0;
}


TESTING DEADBEEF deadbeef efbeadde
Run Code Online (Sandbox Code Playgroud)

这是否产生预期结果?

  • 不:您的工具链和标题已被破坏.
  • 是的:您的工具链没问题,但您的实际代码与示例有所不同.
    通过预处理器运行代码:gcc -dD -E -DLINUX ntoh.cpp,查看ntohl宏扩展到什么,以及它来自何处.

我的猜测是,你有一些愚蠢的事在一个你的头,如

#undef ntohl
#define ntohl(x) (x)
Run Code Online (Sandbox Code Playgroud)