如何知道我应该定义哪个值_POSIX_C_SOURCE?

比方说,我想使用结构timespec,它在time.h中定义.根据联机帮助页,我只需要包含time.h.但是当在c99中编译时,这还不够:

#include <stdio.h>
#include <time.h>

struct timespec abcd;

int main(int argc, char *argv[])
{
   return 0;
}

根据我在网上找到的信息(不在联机帮助页中),我需要添加:

#define _POSIX_C_SOURCE 200809L

所以我有几个问题:

>我怎么知道我需要哪个值_POSIX_C_SOURCE是否相等?我在网上找到了多个值.
>为什么这个定义的位置会影响编译? (参见下文)

#include< stdio.h>

#define _POSIX_C_SOURCE 200809L

#include< time.h>

struct timespec abcd;

int main(int argc,char * argv [])
{
返回0;
}

$gcc test.c -Wall -Wpedantic -std = c99 -o test
test.c:9:25:错误:字段’time_last_package’的类型不完整
struct timespec time_last_package;

汇编得很好:

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <time.h>
....

谢谢

最佳答案

  • How do I know to which value I need _POSIX_C_SOURCE to be equal? I found multiple values online.

每个POSIX标准定义都有一个值.所以你可以使用任何值:

>定义您需要的功能
>您的托管操作系统支持

最好是使用符合这两个标准的最低值.

  • Why does the placement of this definition influence the compilation?

POSIX说:

System Interface Chapter 2. Section 2 The Compilation Environment: A POSIX-conforming application should ensure that the feature test
macro _POSIX_C_SOURCE is defined before inclusion of any header.

否则可能导致错误/不兼容的包含定义…在任何包含之前定义它确保所有都在相同的POSIX版本下…

推荐阅读:The Open Group Base Specifications Issue 7, 2018 edition, 2 – General Information

点赞