cygwin下编译报错 `addrinfo hints‘ has incomplete type and cannot be defined

系统管理员 2022-12-17 07:08 219阅读 0赞

今天在cygwin下编译一个linux项目时报了类似下面的错误:

  1. server.cpp:20: error: aggregate `addrinfo hints' has incomplete type and cannot be defined
  2. server.cpp:25: error: `AI_PASSIVE' was not declared in this scope
  3. server.cpp:27: error: `getaddrinfo' was not declared in this scope
  4. server.cpp:31: error: invalid use of undefined type `struct addrinfo'
  5. server.cpp:20: error: forward declaration of `struct addrinfo'
  6. 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 才有效

  1. #if __POSIX_VISIBLE >= 200112 && !defined(__INSIDE_CYGWIN_NET__)
  2. struct addrinfo {
  3. int ai_flags; /* input flags */
  4. int ai_family; /* address family of socket */
  5. int ai_socktype; /* socket type */
  6. int ai_protocol; /* ai_protocol */
  7. socklen_t ai_addrlen; /* length of socket address */
  8. char *ai_canonname; /* canonical name of service location */
  9. struct sockaddr *ai_addr; /* socket address of socket */
  10. struct addrinfo *ai_next; /* pointer to next in list */
  11. };
  12. #endif

foo.cpp

  1. #include <stdio.h>
  2. #include <sys/socket.h>
  3. #include <netdb.h>
  4. int some_networking_code()
  5. {
  6. addrinfo* addr = NULL;
  7. int flags = AI_NUMERICHOST;
  8. return 0;
  9. }

用如下命令编译上面的代码foo.cpp,可以看到使用-std=c++11__POSIX_VISIBLE 定义为0,而不定义-std-std=gnu++11__POSIX_VISIBLE定义为200809

  1. $ g++ foo.cpp -c -dM -E | grep POSIX_VIS
  2. #define __POSIX_VISIBLE 200809
  3. $ g++ foo.cpp -c -std=c++11 -dM -E | grep POSIX_VIS
  4. #define __POSIX_VISIBLE 0
  5. $ g++ foo.cpp -c -std=gnu++11 -dM -E | grep POSIX_VIS
  6. #define __POSIX_VISIBLE 200809

所以 cygwin下编译c++11代码使用-std=gnu++11代替-std=c++11可以解决类似addrinfo类型未定义问题

发表评论

表情:
评论列表 (有 0 条评论,219人围观)

还没有评论,来说两句吧...

相关阅读