How can I determine if the operating system is POSIX in C?

The Single UNIX Specification requires the existence of unistd.h, which can tell you the POSIX version (via the _POSIX_VERSION macro).

But how can you include unistd.h if you don’t know yet that you are in fact compiling on a UNIX?

That is where this GCC document comes handy. According to it, testing for the presence, or evaluation-to-true of __unix__ should tell you that the system is a UNIX. So:

#ifdef __unix__
/* Yes it is a UNIX because __unix__ is defined.  */

#include <unistd.h>

/* You can find out the version with _POSIX_VERSION.
..
..  */

#endif

__unix__ is not defined on Mac OS X, so to account for that, you could instead do:

#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))

To get a list of system specific predefined macros on your system, you may execute:

cpp -dM /dev/null

For example, my GNU/Linux system also additionally defines __linux__ and __gnu_linux__ apart from __unix__ and a bunch of other stuff.


Another useful document that you must look at is this Wiki.

It goes on to present a way of detecting the presence and version of POSIX in a way similar to the one I described above.


EDIT: Since you really want to do all this because you want to decide which directory separator to use, look at this URL. It says:

Note File I/O functions in the Windows API convert “https://stackoverflow.com/” to “\” as part
of converting the name to an NT-style name, except when using the
“\?\” prefix as detailed in the following sections.

I don’t program on Windows, or know much anything about it, so I can’t say I’ve banked on this.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)