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

yet*_*iba 4 c++ linux automake autoconf

我有一个.cpp档案:htonstest.cpp.我g++用来编译它:

$ g++ -o test htonstest.cpp
Run Code Online (Sandbox Code Playgroud)

它工作,程序./test也有效.

但是,当我使用automake编译它时,有一个编译错误:

 htonstest.cpp: In function ‘int main()’: 
 htonstest.cpp:6: error?expected id-expression before ‘(’ token.
Run Code Online (Sandbox Code Playgroud)

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

重现:

$ aclocal
$ autoheader
$ autoconf
$ automake -a
$ ./configure
$ make
Run Code Online (Sandbox Code Playgroud)

ntohstest.cpp:

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

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

configure.ac:

 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
Run Code Online (Sandbox Code Playgroud)

Makefile.am:

 bin_PROGRAMS=main
 main_SOURCES=htonstest.cpp
Run Code Online (Sandbox Code Playgroud)

Die*_*Epp 8

这实际上与autotools无关,当我测试你的程序时我很惊讶.相关代码在netinet/in.h......

#ifdef __OPTIMIZE__
...
# define ntohs(x) ...
...
#endif
Run Code Online (Sandbox Code Playgroud)

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

修复

ntohs(3)而不是::ntohs(3).

替代修复

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

#undef ntohs
Run Code Online (Sandbox Code Playgroud)

文档

byteorder(3)联机帮助页为:

htons()函数将无符号短整数hostshort从主机字节顺序转换为网络字节顺序.

所以在我看来,这充其量是不礼貌的库来定义一个htons()宏.