../main.c:8:18: error: storage size of ‘hints’ isn’t known
../main.c:13:19: error: ‘AI_PASSIVE’ undeclared (first use in this function)
../main.c:16:3: warning: implicit declaration of function ‘gai_strerror’
看来 gcc 没有与 netdb.h 链接......
这些不是链接错误,并且您不需要 netdb 共享对象
文件(没有这样的野兽;netdb.h
简单地定义数据结构
以及在代码中使用的宏)。
这些是编译器错误: gcc 抱怨因为你正在使用名称
它不认识(AI_PASSIVE
)和数据类型
结构未知(struct addrinfo
).
您提供的代码似乎是正确的,并且addrinfo
定义于/usr/include/netdb.h
。如果你编译它会发生什么
像这样:
gcc -c main.c
你还会有同样的行为吗?如果是这样,请查看输出
的:
gcc -E main.c
这会生成代码的预处理版本,其中包含所有#include
语句替换为其实际内容。你应该
能够 grep 通过这个并查看编译器是否真正得到/usr/include/netdb.h
如果它发现了其他东西:
$ gcc -E foo.c | grep netdb.h | awk '{print $3}' | sort -u
在我的系统上会产生:
"/usr/include/bits/netdb.h"
"/usr/include/netdb.h"
"/usr/include/rpc/netdb.h"
当你添加-ansi
到命令行,你正在改变方式gcc
其行为方式会破坏 Linux 内核和许多系统
头文件。这addrinfo
定义在netdb.h
受到保护
像这样:
#ifdef __USE_POSIX
/* Structure to contain information about address of a service provider. */
struct addrinfo
{
int ai_flags; /* Input flags. */
int ai_family; /* Protocol family for socket. */
int ai_socktype; /* Socket type. */
int ai_protocol; /* Protocol for socket. */
socklen_t ai_addrlen; /* Length of socket address. */
struct sockaddr *ai_addr; /* Socket address for socket. */
char *ai_canonname; /* Canonical name for service location. */
struct addrinfo *ai_next; /* Pointer to next in list. */
};
// ...other stuff...
#endif
当你跑步时gcc
与-ansi
标志,这未定义__USE_POSIX
宏,因为受此保护的东西可能不会
严格符合 ANSI 标准。如果你比较一下你就会发现差异
这:
gcc -E /usr/include/netdb.h
有了这个:
gcc -E -ansi /usr/include/netdb.h
只有前者包含addrinfo
结构。