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

前端 未结 3 729
谎友^
谎友^ 2021-01-31 09:39

Related questions
How can I detect the operating system in C/C++?

How can I find out what operating system I am runni

3条回答
  •  离开以前
    2021-01-31 09:59

    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 
    
    /* 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 "/" 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.

提交回复
热议问题