今天在cygwin下编译一个linux项目时报了类似下面的错误:
server.cpp:20: error: aggregate `addrinfo hints' has incomplete type and cannot be defined server.cpp:25: error: `AI_PASSIVE' was not declared in this scope server.cpp:27: error: `getaddrinfo' was not declared in this scope server.cpp:31: error: invalid use of undefined type `struct addrinfo' server.cpp:20: error: forward declaration of `struct addrinfo' server.cpp:54:2: warning: no newline at end of file显然从字面上看是没有找到addrinfo ,AI_PASSIVE等类型或符号的定义, 几经辗转在stackoverflow上找到下面这个讨论贴:
https://stackoverflow.com/questions/52157480/compiling-with-std-c11-on-cygwin-hides-available-system-calls
在最后发现了答案,原来我写的代码是c++11的所以我在编译选项中加了-std=c++11,而这个回答的意思是在cygwin上应该使用-std=gnu++11,修改后,果然编译通过
以下为进一步验证过程: 在/usr/include/netdb.h找到 addrinfo的定义,可以看到需要 __POSIX_VISIBLE >= 200112 才有效
#if __POSIX_VISIBLE >= 200112 && !defined(__INSIDE_CYGWIN_NET__) struct addrinfo { int ai_flags; /* input flags */ int ai_family; /* address family of socket */ int ai_socktype; /* socket type */ int ai_protocol; /* ai_protocol */ socklen_t ai_addrlen; /* length of socket address */ char *ai_canonname; /* canonical name of service location */ struct sockaddr *ai_addr; /* socket address of socket */ struct addrinfo *ai_next; /* pointer to next in list */ }; #endiffoo.cpp
#include <stdio.h> #include <sys/socket.h> #include <netdb.h> int some_networking_code() { addrinfo* addr = NULL; int flags = AI_NUMERICHOST; return 0; }用如下命令编译上面的代码foo.cpp,可以看到使用-std=c++11时 __POSIX_VISIBLE 定义为0,而不定义-std或-std=gnu++11时__POSIX_VISIBLE定义为200809
$ g++ foo.cpp -c -dM -E | grep POSIX_VIS #define __POSIX_VISIBLE 200809 $ g++ foo.cpp -c -std=c++11 -dM -E | grep POSIX_VIS #define __POSIX_VISIBLE 0 $ g++ foo.cpp -c -std=gnu++11 -dM -E | grep POSIX_VIS #define __POSIX_VISIBLE 200809所以 cygwin下编译c++11代码使用-std=gnu++11代替-std=c++11可以解决类似addrinfo类型未定义问题
