![](/img/trans.png)
[英]GCC with -std=c99 complains about not knowing struct timespec
[英]Why does gcc not complain about htons() but complains about getaddrinfo() when compiled with -std=c99?
即使使用-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);
為什么編譯器不會抱怨htons()
但是在使用-std=c99
編譯時會抱怨getaddrinfo()
?
我正在使用Debian 8.3系統上的gcc 4.9.2編譯這段代碼。
POSIX.1-2001。
htons()
POSIX.1-2001,POSIX.1-2008。 RFC 2553中記錄了getaddrinfo()函數。
由於glibc 2.22:_POSIX_C_SOURCE> = 201112L
Glibc 2.21及更早版本:_POSIX_C_SOURCE
要獲取getaddrinfo()
的原型,您需要在包含標題之前指定要使用的POSIX版本,例如:
#define _POSIX_C_SOURCE 201112L
RFC 2553為套接字接口添加了IPv6支持。 添加意味着添加了新的結構。 由於並非所有的plkatforms都能立即實現新的東西,因此需要指定更改內容所需的接口版本。 htons
在所有版本中都是相同的,因此它不關心您請求的版本。 由於RFC 2553, getaddrinfo
已更改,因此您需要指定您希望/(可以處理)更改的版本。
如評論中所述,_POSIX_C_SOURCE所需的值因平台而異。 似乎對於RHEL6上的gcc,指定_POSIX_SOURCE或_POSIX_C_SOURCE> = 1就足夠了。
如果有人能夠確認_POSIX_SOURCE是否是在任何POSIX系統上獲取getaddrinfo
原型的可移植方式,那將是很棒的。
問題不在getaddrinfo
- 它在struct addrinfo
。 gettaddrinfo
隱式聲明是一個警告,而不是錯誤。 struct addrinfo
未聲明, 這是錯誤。
結構在netdb.h
聲明,但隱藏在ifdef __USE_POSIX
。 有評論:
/ *從POSIX.1g擴展。 * /
對於htons
不存在這樣的ifdef
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.