gpt4 book ai didi

c++ - Linux:ntohl 无法正常工作

转载 作者:IT王子 更新时间:2023-10-29 01:19:43 25 4
gpt4 key购买 nike

我有一个项目需要在 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__

我的编译命令的一部分:

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 ... 

错误是由以下几行产生的:

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

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

最佳答案

The output from those two lines produce same output. TESTING 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

这是否产生了预期的结果?

  • 否:您的工具链和 header 已损坏。
  • 是的:您的工具链没问题,但是您的实际代码与示例中的有些不同。
    通过预处理器运行您的代码:gcc -dD -E -DLINUX ntoh.cpp,并查看 ntohl 宏扩展到的内容以及它的来源。

我的猜测是您在您的 标题之一中有一些愚蠢的东西,例如

#undef ntohl
#define ntohl(x) (x)

关于c++ - Linux:ntohl 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15076977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com