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

How to know to which value I should define _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

所以我有几个问题:

#include <stdio.h>

#define _POSIX_C_SOURCE 200809L

#include <time.h>

struct timespec abcd;

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

$ gcc test.c -Wall -Wpedantic -std=c99 -o test test.c:9:25: error: field ‘time_last_package’ has incomplete type 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 标准定义有一个值。所以你可以使用任何值:

  1. 定义您需要的功能
  2. 您的主机支持 OS

最好使用满足这两个条件的最低值。

  • 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.

否则可能会导致wrong/incompatible包含定义...在定义之前任何包含确保所有都在相同的POSIX版本下...

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

另一个答案提供了很好的背景。但是,也可以在编译器级别定义它,这样您就不必将它放在源代码中。至少使用 gcc 和 glibc,命令行选项

-D_POSIX_C_SOURCE=199309L
如果包含 <time.h>

足以确保 nanosleepstruct timespec 可用。