プリプロセッサ ディレクティブで OS をチェックするにはどうすればよいですか?

OS 用の定義済みマクロ サイトには、チェックの非常に完全なリストがあります。それらのいくつかと、それらが見つかった場所へのリンクを以下に示します:

_WIN32 32ビットと64ビットの両方
_WIN64 64 ビットのみ

Unix (Linux、*BSD、Mac OS X)

このチェックを使用する際の落とし穴については、この関連する質問を参照してください。

unix
__unix
__unix__

Mac OS X

__APPLE__
__MACH__

どちらも定義されています。どちらのチェックも機能するはずです。

Linux

__linux__
linux 廃止されました (POSIX 準拠ではありません)
__linux 廃止されました (POSIX に準拠していません)

FreeBSD

__FreeBSD__

アンドロイド

__ANDROID__


Windows で GCC 定義を表示:

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__ __unix

nadeausoftware と Lambda Fairy の回答に基づいています。

#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 string
const char *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
  • Windows (MinGW)
  • Windows (Cygwin)