Mac OS X、iOS、Linux、Windows でコンパイルする必要があるクロスプラットフォームの C/C++ コードがある場合、プリプロセッサ プロセス中にそれらを確実に検出するにはどうすればよいでしょうか?
ベストアンサー1
ほとんどのコンパイラで使用される定義済みマクロがあります。リストは次の通りです。ここGCCコンパイラの定義済みマクロは、ここ以下は gcc の例です。
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
#ifdef _WIN64
//define something for Windows (64-bit only)
#else
//define something for Windows (32-bit only)
#endif
#elif __APPLE__
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR
// iOS, tvOS, or watchOS Simulator
#elif TARGET_OS_MACCATALYST
// Mac's Catalyst (ports iOS API into Mac, like UIKit).
#elif TARGET_OS_IPHONE
// iOS, tvOS, or watchOS device
#elif TARGET_OS_MAC
// Other kinds of Apple platforms
#else
# error "Unknown Apple platform"
#endif
#elif __ANDROID__
// Below __linux__ check should be enough to handle Android,
// but something may be unique to Android.
#elif __linux__
// linux
#elif __unix__ // all unices not caught above
// Unix
#elif defined(_POSIX_VERSION)
// POSIX
#else
# error "Unknown compiler"
#endif
定義されるマクロは、使用するコンパイラによって異なります。
は、Windows x64 バージョンをターゲットとする場合でも定義されているため、に_WIN64
#ifdef
ネストできます。これにより、一部のヘッダー インクルードが両方に共通している場合にコードの重複を防ぐことができます (また、アンダースコアがないため、IDE はコードの適切なパーティションを強調表示できます)。_WIN32
#ifdef
_WIN32
WIN32