【问题标题】:C++: ::ntohs() fails on higher optimization levelsC++: ::ntohs() 在更高的优化级别上失败
【发布时间】:2013-01-04 02:27:45
【问题描述】:

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

Makefile.am:

 bin_PROGRAMS=main
 main_SOURCES=htonstest.cpp

【问题讨论】:

  • 尝试添加using namespace std;
  • @JohnTortugo:不错的猜测,但没有。
  • 什么资源告诉你使用::ntohs
  • zh,好问题,我也不知道。我认为只有一个原因:(旧代码):-)。
  • @LightnessRacesinOrbit :这是从 Windows 移植的一些代码,而不仅仅是一些“旧代码”。据我所知,"::ntohs" 在 Windows 中是正确的。

标签: c++ linux autoconf automake


【解决方案1】:

这实际上与自动工具无关,当我测试您的程序时,我感到非常惊讶。相关代码在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() 宏充其量是粗鲁

【讨论】:

  • 哦,太好了,谢谢,你告诉我原因。非常感谢。
  • " 所以在我看来,库定义一个 htons() 宏充其量是粗鲁的。” 实际上,POSIX 说“以下 [(htonl, htons, ntohs, nothl)] 应该被声明为函数,或定义为宏,或两者兼而有之。如果声明了函数,则应提供函数原型。 pubs.opengroup.org/onlinepubs/9699919799/basedefs/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-28
  • 1970-01-01
  • 2020-12-01
  • 2011-10-26
  • 1970-01-01
  • 2022-11-10
  • 2016-01-01
相关资源
最近更新 更多