Reputation:
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
Upvotes: 13
Views: 3040
Reputation: 1744
The other answer gives nice background. But, it's also possible to define this at the compiler level so you don't have to put it in your source. With gcc
and glibc at least, the command-line option
-D_POSIX_C_SOURCE=199309L
is enough to ensure that nanosleep
and struct timespec
are available if you include <time.h>
.
Upvotes: 1
Reputation: 36431
- 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:
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
Upvotes: 6