为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用预处理器指令检查OS?

如何使用预处理器指令检查OS?

C
慕码人2483693 2019-07-22 14:53:00
如何使用预处理器指令检查OS?我需要我的代码根据编译它的操作系统来做不同的事情。我在找这样的东西:#ifdef OSisWindows// do Windows-specific stuff#else// do Unix-specific stuff#endif有办法吗?有更好的方法来做同样的事情吗?
查看完整描述

3 回答

?
GCT1015

TA贡献1827条经验 获得超4个赞

这个操作系统的预定义宏站点有一个非常完整的检查列表。下面是其中的一些,并提供了找到它们的链接:

_WIN3232位和64位
_WIN6464位

Unix(Linux,*BSD,MacOSX)

看这个相关问题在使用这张支票的一些缺陷上。

unix
__unix
__unix__

MacOSX

__APPLE__
__MACH__

两者都已定义;检查两者都应该有效。

linux

__linux__
linux过时(不符合POSIX标准)
__linux过时(不符合POSIX标准)

FreeBSD

__FreeBSD__


查看完整回答
反对 回复 2019-07-22
?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

GCC在Windows上定义:

gcc -dM -E - <NUL:

在Linux上:

gcc -dM -E - </dev/null

MinGW中预定义的宏:

WIN32 _WIN32 __WIN32 __WIN32__ __MINGW32__ WINNT __WINNT __WINNT__ _X86_ i386 __i386

关于统一:

unix __unix__ __unix


查看完整回答
反对 回复 2019-07-22
?
智慧大石

TA贡献1946条经验 获得超3个赞

基于nadeausofware朗达仙女的回答.

#include <stdio.h>/**
 * Determination a platform of an operation system
 * Fully supported supported only GNU GCC/G++, partially on Clang/LLVM
 */#if defined(_WIN32)
    #define PLATFORM_NAME "windows" // Windows#elif defined(_WIN64)
    #define PLATFORM_NAME "windows" // Windows#elif defined(__CYGWIN__) && !defined(_WIN32)
    #define PLATFORM_NAME "windows" // Windows (Cygwin POSIX under Microsoft Window)#elif defined(__ANDROID__)
    #define PLATFORM_NAME "android" // Android (implies Linux, so it must come first)#elif defined(__linux__)
    #define PLATFORM_NAME "linux" // Debian, Ubuntu, Gentoo, Fedora, openSUSE, RedHat, Centos and other#elif defined(__unix__) || defined(__APPLE__) && defined(__MACH__)
    #include <sys/param.h>
    #if defined(BSD)
        #define PLATFORM_NAME "bsd" // FreeBSD, NetBSD, OpenBSD, DragonFly BSD
    #endif#elif defined(__hpux)
    #define PLATFORM_NAME "hp-ux" // HP-UX#elif defined(_AIX)
    #define PLATFORM_NAME "aix" // IBM AIX#elif defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin)
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR == 1
        #define PLATFORM_NAME "ios" // Apple iOS
    #elif TARGET_OS_IPHONE == 1
        #define PLATFORM_NAME "ios" // Apple iOS
    #elif TARGET_OS_MAC == 1
        #define PLATFORM_NAME "osx" // Apple OSX
    #endif#elif defined(__sun) && defined(__SVR4)
    #define PLATFORM_NAME "solaris" // Oracle Solaris, Open Indiana#else
    #define PLATFORM_NAME NULL#endif// Return a name of platform, if determined, otherwise - an empty stringchar *get_platform_name() {
    return (PLATFORM_NAME == NULL) ? "" : PLATFORM_NAME;}int main(int argc, char *argv[]) {
    puts(get_platform_name());
    return 0;}

用GCC和Clang测试:

  • Debian 8
  • 窗户(MinGW)
  • 窗口(Cygwin)


查看完整回答
反对 回复 2019-07-22
  • 3 回答
  • 0 关注
  • 500 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信