C ++: ntohs () fails at higher optimization levels

I have a .cpp file: htonstest.cpp . I use g++ to compile it:

 $ g++ -o test htonstest.cpp 

It works, and the ./test program works too.

But, when I use automake to compile it, it has a compilation error:

  htonstest.cpp: In function 'int main()': htonstest.cpp:6: error๏ผšexpected id-expression before '(' token. 

My OS is CentOS, gcc version is 4.1.2 20080704, autoconf version is 2.59, automake version is 1.9.6.

Playback:

 $ 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; } 

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 

Makefile.am:

  bin_PROGRAMS=main main_SOURCES=htonstest.cpp 
+4
source share
1 answer

This is not actually related to autotools, and I was very surprised when I tested your program. The corresponding code is in netinet/in.h ...

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

The reason code doesn't work in Automake is because Automake defaults to -O2 , and when -O2 turned on, ntohs() is a macro.

Correction

Use ntohs(3) instead of ::ntohs(3) .

Alternative solution

Add the following line after inclusion:

 #undef ntohs 

Documentation

The page mask byteorder(3) reads:

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

So, in my opinion, in the best case for the library you need to define the htons() macro.

+7
source

All Articles