搜索一个问题 C、C++判断操作系统 是 Linux还是windows 还是Unix【编译器内置宏 探索(不是特别满意)】

得到的答案 都不好。为什么,因为他们都不知道原理。其实原理很简单,编译器 参数或Makefile添加了宏定义,你才可以这样去判断。

比如编译器设置了宏 is_windows,你才能去用。不设置没法用。

但是,我敢肯定各种编译器 内置一些宏,比如 MS VC的cl.exe ,LINUX的GNU gcc,在各个平台都会有不同的内置宏的。

所以 如果我搜索 "各个编译器 内置宏 操作系统" 少量的答案中 有一个 :

C++:编写跨平台程序的关键,C/C++中的内置宏定义
分两部分:

操作系统判定:

Windows:   WIN32

Linux:   linux

Solaris:   __sun

编译器判定:

VC:  _MSC_VER

GCC/G++:   __GNUC__

SunCC:   __SUNPRO_C和__SUNPRO_CC

 

转载自:http://blog.csdn.net/avagrant158/article/details/6298145

还算凑合,但是还不够,各个编译器 到底内置那些宏,我们怎么才能知道呢?你得告诉我方法啊,没法弄,有空了去msdn查查(也不一定能查到,他们不一定说的),gcc可以看源代码,但是那么多代码,老费劲了。

 下面 根据这个,我写了个跨平台的C++程序。不过 _UNIX WINDOWS俩宏  暂时是错误的。不会输出

 testDefineOS.cpp源码

#include <stdio.h>

#include <iostream>



using namespace std;



int main(int argc,char **argv){

    int no_os_flag=1;

    #ifdef linux

       no_os_flag=0;

       cout<<"It is in Linux OS!"<<endl;

    #endif

    #ifdef _UNIX

       no_os_flag=0;

       cout<<"It is in UNIX OS!"<<endl;

    #endif

    #ifdef __WINDOWS_

       no_os_flag=0;

       cout<<"It is in Windows OS!"<<endl;

    #endif

    #ifdef _WIN32

       no_os_flag=0;

       cout<<"It is in WIN32 OS!"<<endl;

    #endif

    if(1==no_os_flag){

        cout<<"No OS Defined ,I do not know what the os is!"<<endl;

    }

    return 0;

}

在win /Linux 使用 MS VC cl.exe编译器(不知道如何称呼cl.exe,大家一般不这么叫吧,但是gcc确实可以那么叫),和 gcc编译器的结果

Win Cl.exe编译器结果
==============
D:\>cl.exe testDefineOS.cpp
用于 80x86 的 Microsoft (R) 32 位 C/C++ 优化编译器 16.00.40219.01 版
版权所有(C) Microsoft Corporation。保留所有权利。

testDefineOS.cpp
C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\INCLUDE\xlocale(323) : wa
rning C4530: 使用了 C++ 异常处理程序,但未启用展开语义。请指定 /EHsc
Microsoft (R) Incremental Linker Version 10.00.40219.01
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:testDefineOS.exe
testDefineOS.obj

D:\>testDefineOS.exe
It is in WIN32 OS!

D:\>






Linux GCC编译器结果
==================
ayanmw@ayanmw-desktop:~$ g++ test    testDefineOS.cpp ;./a.out
It is in Linux OS!
ayanmw@ayanmw-desktop:~$ 




Windows GCC.exe(MINGW)
=======================
D:\>g++ testDefineOS.cpp

D:\>a.exe
It is in WIN32 OS!

D:\>

关于 C中的预编译宏定义 还请看http://os.chinaunix.net/a2008/1216/989/000000989777.shtml

原文地址:https://www.cnblogs.com/ayanmw/p/2600911.html