How do I check OS with a preprocessor directive?

前端 未结 16 1344
星月不相逢
星月不相逢 2020-11-22 13:53

I need my code to do different things based on the operating system on which it gets compiled. I\'m looking for something like this:

#ifdef OSisWindows
// do         


        
相关标签:
16条回答
  • 2020-11-22 14:04
    #ifdef _WIN32
    // do something for windows like include <windows.h>
    #elif defined __unix__
    // do something for unix like include <unistd.h>
    #elif defined __APPLE__
    // do something for mac
    #endif
    
    0 讨论(0)
  • 2020-11-22 14:06

    You can use pre-processor directives as warning or error to check at compile time you don't need to run this program at all just simply compile it .

    #if defined(_WIN32) || defined(_WIN64) || defined(__WINDOWS__)
        #error Windows_OS
    #elif defined(__linux__)
        #error Linux_OS
    #elif defined(__APPLE__) && defined(__MACH__)
        #error Mach_OS
    #elif defined(unix) || defined(__unix__) || defined(__unix)
        #error Unix_OS
    #else
        #error Unknown_OS
    #endif
    
    #include <stdio.h>
    int main(void)
    {
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-22 14:08

    I wrote an small library to get the operating system you are on, it can be installed using clib (The C package manager), so it is really simple to use it as a dependency for your projects.

    Install

    $ clib install abranhe/os.c
    

    Usage

    #include <stdio.h>
    #include "os.h"
    
    int main()
    {
        printf("%s\n", operating_system());
        // macOS
        return 0;
    }
    

    It returns a string (char*) with the name of the operating system you are using, for further information about this project check it out the documentation on Github.

    0 讨论(0)
  • 2020-11-22 14:09

    In most cases it is better to check whether a given functionality is present or not. For example: if the function pipe() exists or not.

    0 讨论(0)
  • 2020-11-22 14:10

    I did not find Haiku definition here. To be complete, Haiku-os definition is simple __HAIKU__

    0 讨论(0)
  • 2020-11-22 14:13

    Just to sum it all up, here are a bunch of helpful links.

    • GCC Common Predefined Macros
    • SourceForge predefined Operating Systems
    • MSDN Predefined Macros
    • The Much-Linked NaudeaSoftware Page
    • Wikipedia!!!
    • SourceForge's "Overview of pre-defined compiler macros for standards, compilers, operating systems, and hardware architectures."
    • FreeBSD's "Differentiating Operating Systems"
    • All kinds of predefined macros
    • libportable
    0 讨论(0)
提交回复
热议问题