【发布时间】:2017-01-17 12:03:42
【问题描述】:
即使使用-std=c99 编译,以下程序也能正常编译和运行。
#include <stdio.h>
#include <arpa/inet.h>
int main()
{
printf("%d\n", htons(1));
}
这是输出。
$ gcc -std=c99 foo.c && ./a.out
256
但是下面的程序会导致警告和错误。
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main()
{
struct addrinfo *res;
getaddrinfo("localhost", NULL, NULL, &res);
printf("%d\n", res->ai_flags);
}
这是警告和错误。
$ gcc -std=c99 bar.c
bar.c: In function ‘main’:
bar.c:9:5: warning: implicit declaration of function ‘getaddrinfo’ [-Wimplicit-function-declaration]
getaddrinfo("localhost", NULL, NULL, &res);
^
bar.c:10:23: error: dereferencing pointer to incomplete type
printf("%d\n", res->ai_flags);
为什么编译器在用-std=c99编译时不抱怨htons(),而是抱怨getaddrinfo()?
我在 Debian 8.3 系统上使用 gcc 4.9.2 编译此代码。
【问题讨论】:
-
我对这些库一无所知,但似乎是一些库安装问题。
-
@Lundin 这不是库安装问题。我没有安装这些库。它是系统自带的。这是关于 C99 与 POSIX 的问题,因为我已经在这个问题中标记了。如果我从编译器选项中省略
-std=c99,第二个代码示例将编译得很好。 -
getaddrinfo 在 1999 年不存在
-
如果添加
-D_POSIX_C_SOURCE=200809L会发生什么?在严格的 c99 模式下,标头可能有一个隐藏这些声明的条件。 -
@stark
htons也没有。那为什么会编译呢?