c++ - 如何在运行时检测 C 中的操作系统

标签 c++ c c-preprocessor

我知道这并不简单,我已经研究了一段时间,现在我几乎可以肯定没有完全安全的方法。但就是这样。 我正在寻找一种方法来了解我的应用程序在哪个操作系统上运行。到目前为止,我得到了这个:

#if defined(__WIN64__) || defined(__WIN64) || defined(WIN64)
    #define NLF_OS_WINDOWS
    #define NLF_OS_64BITS
#elif defined(__WIN32__) || defined(__WIN32) || defined(WIN32)
    #define NLF_OS_WINDOWS
    #define NLF_OS_32BITS
#elif defined(unix) || defined(__unix__) || defined(__unix)
    #define NLF_OS_UNIX
    #if defined(__APPLE__)
        #define NLF_OS_APPLE
        #define NLF_OS_BITS_UNIDENTIFIED
        #include <TargetConditionals.h>
        #if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
            #define NLF_OS_SIMULATOR
        #elif TARGET_OS_IPHONE
            #define NLF_OS_IPHONE
        #else
            #define NLF_OS_OSX
        #endif
    #elif defined(__linux__) || defined(__linux) || defined(linux)
        #define NLF_OS_LINUX
        #if defined(i386) || defined(__i386) || defined(__i386__)
            #define NLF_OS_32BITS
        #elif defined(amd64)  || defined(__amd64) || defined(__amd64__)
            #define NLF_OS_64BITS
        #endif
    #elif defined(__FreeBSD__) || defined(__FreeBSD) || defined(FreeBSD)
        #define NLF_OS_FREEBSD
        #if defined(i386) || defined(__i386) || defined(__i386__)
            #define NLF_OS_32BITS
        #elif defined(amd64)  || defined(__amd64) || defined(__amd64__)
            #define NLF_OS_64BITS
        #endif
    #endif
#else
    #define NLF_OS_UNIDENTIFIED
    #define NLF_OS_BITS_UNIDENTIFIED
#endif

它已经有所帮助,但它只是在我编译应用程序时告诉我系统是什么。但是,由于我想交叉编译我正在做的事情,如果我可以为应用程序提供一种方法来了解哪个是当前运行的系统,那将非常有用。明白了吗?

也许我可能会使用库 sys/“something”(如 sys/types.h 和 sys/stat.h)来做一些丑陋的事情,但我几乎不知道这些事情。

PS.: C++ 解决方案并不是我想要的,但在这么高的水平上,我正在努力 ^^"

最佳答案

终于回答了这个问题。

答案是:您不需要。我注意到了。定义已经工作得很好。如果您正在为另一个平台编译 C 代码,交叉编译器将负责重新定义定义,因此如果您使用预处理器指令,您的系统将始终知道系统是什么。

但如果出于某种原因你真的需要它,你将不得不做丑陋的事情。比如使用 system("uname -a > my_file"); 然后读取 my_file 内容,如果这个命令不起作用,然后尝试另一个命令。

主要是,你不需要它 =)

关于c++ - 如何在运行时检测 C 中的操作系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37470715/

相关文章:

通过 MAC Winsock2 连接到服务器

c - 如何使用 ifdef 检测英特尔的编译器 (ICC)?

c++ - 从 QT 资源加载 openCV Haar Cascade

c - 当结构定义具有指针时分配结构

.net - 更改/添加控件到窗口打开/保存通用对话框

c - 即使在我使用 malloc() 分配内存后,free() 也无法正常工作

c - 如何使用 Makefile 将多个文件提供给后台进程

c - 有了#define 值替换列表,如何将值解析为标识符的字符串?

c++ - 为什么 detectMultiScale 不返回面孔?

c++ - For 循环不停止