Determine if Linux or Windows in C++

后端 未结 6 1879
忘了有多久
忘了有多久 2021-02-04 00:40

I am writing a cross-platform compatible function in C++ that creates directories based on input filenames. I need to know if the machine is Linux or windows and use the appropr

相关标签:
6条回答
  • 2021-02-04 00:48

    Look into http://en.wikipedia.org/wiki/Uname

    If you are using g++ as your compiler/GNU then you could try the code below. POSIX compliant environments support this:

    #include <stdio.h>
    #include <sys/utsname.h>
    #include <stdlib.h>
    
    int main()
    {
        struct utsname sysinfo;
        if(uname(&sysinfo)) exit(9);
        printf("os name: %s\n", sysinfo.sysname);
        return 0;
    }
    
    0 讨论(0)
  • 2021-02-04 00:59

    By default, Visual Studio #defines _WIN32 in the preprocessor project settings.

    So you can use

    // _WIN32 = we're in windows
    #ifdef _WIN32
    // Windows
    #else
    // Not windows
    #endif
    
    0 讨论(0)
  • 2021-02-04 01:01

    Use:

    #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
    static const std::string slash="\\";
    #else
    static const std::string slash="/";
    #endif
    

    BTW, you can still safely use this slash "/" on Windows as windows understands this perfectly. So just sticking with "/" slash would solve problems for all OSes even like OpenVMS where path is foo:[bar.bee]test.ext can be represented as /foo/bar/bee/test.ext.

    0 讨论(0)
  • 2021-02-04 01:02

    Generally speaking, you'd have do do this with conditional compilation.

    That said, if you're using boost::filesystem you should be using the portable generic path format so that you can forget about things like this.

    0 讨论(0)
  • 2021-02-04 01:04

    One of the most used methods to do this is with a pre-processor directive. The link is for C but they're used the same way in C++. Fair warning, each compiler & OS can have their own set of directives.

    0 讨论(0)
  • 2021-02-04 01:04

    predef.sourceforge.net is a comprehensive collection of all kinds of MACROs that identify compilers/operating systems and more. (linking directly to the operating system sub-site)

    0 讨论(0)
提交回复
热议问题