gpt4 book ai didi

C++:::ntohs() 在更高的优化级别上失败

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

我有一个.cpp 文件:htonstest.cpp。我使用 g++ 编译它:

$ g++ -o test htonstest.cpp

它有效,程序 ./test 也有效。

但是,当我使用 automake 编译它时,出现编译错误:

 htonstest.cpp: In function ‘int main()’: 
htonstest.cpp:6: error:expected id-expression before ‘(’ token.

我的操作系统是CentOS,gcc的版本是4.1.2 20080704,autoconf的版本是2.59,automake的版本是1.9.6。

重现:

$ aclocal
$ autoheader
$ autoconf
$ automake -a
$ ./configure
$ make

ntohstest.cpp:

 #include <netinet/in.h>
#include <iostream>

int main()
{
short a = ::ntohs(3);
std::cout << a << std::endl;
std::cin.get();
return 0;
}

配置文件:

 AC_PREREQ(2.59)
AC_INIT(FULL-PACKAGE-NAME, VERSION, BUG-REPORT-ADDRESS)
AC_CONFIG_SRCDIR([htonstest.cpp])
AC_CONFIG_HEADER([config.h])
AM_INIT_AUTOMAKE([foreign])
# Checks for programs.
AC_PROG_CXX

# Checks for libraries.

# Checks for header files.
# AC_CHECK_HEADERS([netinet/in.h])

# Checks for typedefs, structures, and compiler characteristics.

# Checks for library functions.
AC_CONFIG_FILES(Makefile)
AC_OUTPUT

生成文件.am:

 bin_PROGRAMS=main
main_SOURCES=htonstest.cpp

最佳答案

这实际上与 autotools 无关,我在测试您的程序时感到非常惊讶。相关代码在netinet/in.h...

#ifdef __OPTIMIZE__
...
# define ntohs(x) ...
...
#endif

代码在Automake下失败的原因是因为Automake默认为-O2,当启用-O2时,ntohs()是一个宏。

修复

使用 ntohs(3) 而不是 ::ntohs(3)

替代修复

在您的包含之后添加以下行:

#undef ntohs

文档

byteorder(3) 联机帮助页显示:

The htons() function converts the unsigned short integer hostshort from host byte order to network byte order.

所以在我看来,图书馆定义 htons() 宏至多是粗鲁

关于C++:::ntohs() 在更高的优化级别上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14431776/

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