Search code examples
cposix

How to know to which value I should define _POSIX_C_SOURCE?


Let's say for instance I want to use the structure timespec, which is defined in time.h. According to the manpages I only need to include time.h. But when compiling in c99, this isn't enough:

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

struct timespec abcd;

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

According to the info I find online (not in the manpages), I need to add this:

#define _POSIX_C_SOURCE 200809L

So I have a few questions:

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

  • Why does the placement of this definition influence the compilation? (cf . infra)

#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;

compiles well:

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

Thanks


Solution

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

    There is one value per POSIX standard definition. So you can use any value which:

    1. defines the functionality you need
    2. is supported by your hosting OS

    Best is to use the lowest value that meet both those criteria.

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

    POSIX says :

    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.

    Otherwise it may leads to wrong/incompatible included definitions... Defining it before any include ensure that all is under the same POSIX version...

    Recommended reading : The Open Group Base Specifications Issue 7, 2018 edition, 2 - General Information