Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use POSIX functions with -std flag with GCC?

Tags:

c

posix

gcc

My code uses nanosleep(). It compiles fine. And now if I try to compile it with -std=c23 flag, nanosleep() isn't recognized.

Any other major C standard version doesn't work. I tried using various versions of _POSIX_C_SOURCE both in code, and compile options, but that too doesn't work.

like image 602
Programmer_2147483647 Avatar asked Oct 26 '25 15:10

Programmer_2147483647


2 Answers

The -std option values calling out a specific standard, i.e. c89, c99, c11, c23, don't include many GNU or POSIX specific functions.

There are alternate values for those standard versions that do include these, i.e. gnu89 gnu99, gnu11, gnu23.

like image 179
dbush Avatar answered Oct 29 '25 04:10

dbush


My code uses nanosleep(). It compiles fine. And now if I try to compile it with -std=c23 flag, nanosleep() isn't recognized.

That's to be expected. nanosleep() is not defined by ISO C, and -std=c23 prevents non-ISO functions from being declared by default.

I tried using various versions of _POSIX_C_SOURCE both in code, and compile options, but that too doesn't work.

Apparently you didn't find the right one, or else you didn't apply it correctly. This compiles without warnings for me with -std=c17 (my version of GCC is too old for -std=c23), and works as expected:

#define _POSIX_C_SOURCE 199309L

#include <time.h>

int main(void) {
    nanosleep(&(struct timespec){ .tv_sec = 2 }, NULL);
}

Note well that the definition of _POSIX_C_SOURCE appears at the very top, before any headers are included.

The Linux documentation for nanosleep() told me what value I needed for _POSIX_C_SOURCE. You could also refer to the GCC manual for the feature test macros and values recognized by GCC. If you want C23 conformance and the latest POSIX extensions as of the current GCC and glibc, but not any non-POSIX extensions, then you could define _POSIX_C_SOURCE to 200809L (and continue compiling with -std=c23).

But if you just want C23 syntax and feature support without limiting what library features are available, then the strict-conformance compile modes are counterproductive for you. In that case, you are probably looking for the versioned GNU-source modes, such as -std=gnu23.

like image 31
John Bollinger Avatar answered Oct 29 '25 04:10

John Bollinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!