015-编译器内置宏-判断操作系统

本文介绍了一种使用预处理指令进行跨平台编译的方法,并通过示例代码展示了如何根据不同操作系统输出特定信息。针对Windows、MacOS及Linux等平台进行了测试。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


#define THE_NUM 3
#define WIN 1
#define LINUX 2
#define MAC 3

void sayHello(){
    #if PLATFORM == WIN
        printf("Hello Windows\n");
    #elif PLATFORM == Linux
        printf("Hello Linux\n");
    #elif PLATFORM == MAC
        printf("Hello Mac\n");
    #else
        printf("Unknown Platform");
    #endif
}

int main(){
    printf("The num is %d\n", THE_NUM);
    sayHello();
    return EXIT_SUCCESS;
}

输出如下:

The num is 3
Hello Linux

但是经过测试时不准确的,经过查看其它资料,验证如下

int main(){
    printf("The num is %d\n", THE_NUM);
    sayHello();
    #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)
         printf("It's _WIN64 ");
        #else
        //define something for Windows (32-bit only)
         printf("It's something for Windows-32 ");
        #endif
    #elif __APPLE__
        #include <TargetConditionals.h>
        #if TARGET_IPHONE_SIMULATOR
        // iOS Simulator
        printf("It's iOS Simulator ");
        #elif TARGET_OS_IPHONE
        // iOS device
        printf("It's TARGET_OS_IPHONE ");
        #elif TARGET_OS_MAC
        // Other kinds of Mac OS
        printf("It's TARGET_OS_MAC \n");
        #else
        #error "Unknown Apple platform"
        #endif
    #elif __linux__
        // linux
        printf("It's __linux__ ");
    #elif __unix__ // all unices not caught above
        // Unix
        printf("It's __unix__ ");
    #elif defined(_POSIX_VERSION)
        // POSIX
        printf("It's POSIX ");
    #else
    #   error "Unknown compiler"
    #endif
    return EXIT_SUCCESS;
}

在MacOS中进行测试,输出如下:

The num is 3
Hello Linux
It's TARGET_OS_MAC 

在CentOS7中进行测试,输出如下:

The num is 3
Hello Linux
It's __linux__

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值