6

我有一个.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:

 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
4

1 回答 1

11

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

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

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

修复

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

替代修复

在包含后添加以下行:

#undef ntohs

文档

byteorder(3)手册页内容如下:

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

所以在我看来,图书馆定义宏充其量是粗鲁的。htons()

于 2013-01-21T02:45:19.413 回答