【发布时间】:2011-09-27 15:41:05
【问题描述】:
我正在尝试编译此程序,如第 19 页的 Beej 网络编程指南 中所述。
#include <stdio.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
int main() {
int status;
struct addrinfo hints;
struct addrinfo *servinfo; /* Will point to the results */
memset(&hints, 0, sizeof hints); /* Make sure the struct is empty */
hints.ai_family = AF_UNSPEC; /* Don't care IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
if ((status = getaddrinfo(NULL, "3490", &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
/* Servinfo now points to a linked list of 1 or more struct addrinfos
... do everything until you don't need servinfo anymore .... */
freeaddrinfo(servinfo); /* Free the linked-list */
return 0;
}
在其他错误中,我看到了
../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 链接。 Eclipse 是我用来构建它的 IDE,它可以毫不费力地找到该文件。这是编译器命令:
gcc -O0 -g3 -pedantic -Wall -c -fmessage-length=0 -ansi -MMD -MP -MF"main.d" -MT"main.d" -o"main.o" "../main.c"
添加-lnetdb 并不能解决问题。还有……
~> find /usr/include/ -name netdb.h
/usr/include/bits/netdb.h
/usr/include/gssrpc/netdb.h
/usr/include/netdb.h
/usr/include/rpc/netdb.h
我认为这些文件预装在我的 openSUSE 主机上。为什么 gcc 检测不到 netdb.h?还是我得出了错误的结论?
【问题讨论】:
-
我在 Linux Mint 20 上遇到了类似的问题。我的 IDE(VS 代码)无法识别 addrinfo 结构,并且在编译时出现以下错误:gethost.c: In function 'main ':gethost.c:52:5:警告:函数'freehostent'的隐式声明;你是说 /usr/bin/ld: /tmp/ccNUFQ8z.o: in function
main': gethost.c:(.text+0x2ad): undefined reference tofreehostent' collect2: error: ld returned 1 exit status 这个完全相同的源文件在 MacOS 10.14 上编译得很好。
标签: c networking linker