前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >cygwin下编译报错 `addrinfo hints‘ has incomplete type and cannot be defined

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

作者头像
10km
发布2020-10-29 10:43:16
1.9K0
发布2020-10-29 10:43:16
举报
文章被收录于专栏:10km的专栏

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

代码语言:javascript
复制
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 才有效

代码语言:javascript
复制
#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 */
};
#endif

foo.cpp

代码语言:javascript
复制
#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

代码语言:javascript
复制
$ 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类型未定义问题

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/10/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档