当我尝试编译代码时,出现以下错误:
main.c:13:40: note: each undeclared identifier is reported only once for each function it appears in
main.c:17:14: error: ‘EAI_ADDRFAMILY’ undeclared (first use in this function); did you mean ‘EAI_FAMILY’?
case EAI_ADDRFAMILY:
^~~~~~~~~~~~~~
EAI_FAMILY
main.c:29:14: error: ‘EAI_NODATA’ undeclared (first use in this function); did you mean ‘EAI_NONAME’?
case EAI_NODATA:
^~~~~~~~~~
EAI_NONAME
我尝试包括不同的标头(例如netinet/in.h
)以及使用不同的标准(gnu90
,gnu99
,gnu11
)进行编译,但似乎没有任何解决方法错误。
以下是我的代码:
// Name: main.c
// Compile: gcc -std=gnu11 main.c
// Error:
// main.c: In function ‘main’:
// main.c:18:14: error: ‘EAI_ADDRFAMILY’ undeclared (first use in this function); did you mean ‘EAI_FAMILY’?
// case EAI_ADDRFAMILY:
// ^~~~~~~~~~~~~~
// EAI_FAMILY
// main.c:18:14: note: each undeclared identifier is reported only once for each function it appears in
// main.c:30:14: error: ‘EAI_NODATA’ undeclared (first use in this function); did you mean ‘EAI_NONAME’?
// case EAI_NODATA:
// ^~~~~~~~~~
// EAI_NONAME
#include <stddef.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main()
{
struct addrinfo* res;
char* domain = "google.com";
switch(getaddrinfo(domain, "http", NULL, &res))
{
case 0:
break;
case EAI_ADDRFAMILY:
break;
case EAI_AGAIN:
break;
case EAI_BADFLAGS:
break;
case EAI_FAIL:
break;
case EAI_FAMILY:
break;
case EAI_MEMORY:
break;
case EAI_NODATA:
break;
case EAI_NONAME:
break;
case EAI_SERVICE:
break;
case EAI_SOCKTYPE:
break;
}
return 0;
}
答案 0 :(得分:1)
事实证明,尽管EAI_ADDRFAMILY
和EAI_NODATA
这两个定义是在我的系统上的netdb.h
中定义的,但它们未启用,因为需要定义__USE_GNU
。
要(间接)启用__USE_GNU
,我们在文件顶部定义_GNU_SOURCE
。工作文件如下:
// Name: main.c
// Compile: gcc -std=gnu11 main.c
#define _GNU_SOURCE // Need for EAI_ADDRFAMILY and EAI_NODATA
#include <stddef.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main()
{
struct addrinfo* res;
char* domain = "google.com";
switch(getaddrinfo(domain, "http", NULL, &res))
{
case 0:
break;
case EAI_ADDRFAMILY:
break;
case EAI_AGAIN:
break;
case EAI_BADFLAGS:
break;
case EAI_FAIL:
break;
case EAI_FAMILY:
break;
case EAI_MEMORY:
break;
case EAI_NODATA:
break;
case EAI_NONAME:
break;
case EAI_SERVICE:
break;
case EAI_SOCKTYPE:
break;
}
return 0;
}