C++ 是否有任何宏可以确定我的代码是否正在编译到 Windows?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/430424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:18:42  来源:igfitidea点击:

Are there any macros to determine if my code is being compiled to Windows?

c++coperating-systemc-preprocessor

提问by batty

I would like to detect whether the OS I'm compiling on is Windows. Is there a simple macro I can check to verify that?

我想检测我正在编译的操作系统是否是 Windows。我可以检查一个简单的宏来验证吗?

采纳答案by phord

[Edit: I assume you want to use compile-time macros to determine which environment you're on. Maybe you want to determine if you're running on Wine under Linux or something instead of Windows, but in general, your compiler targets a specific environment, and that is either Windows (DOS) or it isn't, but it's rarely (never?) both.]

[编辑:我假设您想使用编译时宏来确定您所在的环境。也许你想确定你是在 Linux 下运行 Wine 还是其他东西而不是 Windows,但一般来说,你的编译器针对特定环境,要么是 Windows (DOS),要么不是,但很少(从不?) 两个都。]

Some compilers offer macros to indicate a Windows build environment. But these will vary from compiler to compiler, and even on the same compiler on Windows if the target environment is notexclusively windows. Usually it's __WIN32__, but not always.

一些编译器提供宏来指示 Windows 构建环境。但是这些会因编译器而异,如果目标环境完全是 Windows,甚至在 Windows 上的同一个编译器上也会有所不同。通常是__WIN32__,但并非总是如此。

#if defined (__WIN32__)
  // Windows stuff
#endif

Sometimes it can be _WIN32, __CYGWIN32__, or possibly just the compiler indicator (_MSC_VER).

有时它可以是_WIN32__CYGWIN32__或可能只是编译器指示符 ( _MSC_VER)。

If you know the environment you'll be building in (from the makefile) then you can usually pass in the #defineon the command line, like "g++ -D __WIN32__ yourfile.c".

如果您知道将要构建的环境(从 makefile 中),那么您通常可以#define在命令行中传入,例如“ g++ -D __WIN32__ yourfile.c”。

A little more info here

这里有更多信息

回答by JesperE

There are a number of different ways to detect compilation, host, and runtime environments. All depending on exactly what you want to know. There are three broad types of environments:

有多种不同的方法可以检测编译、宿主和运行时环境。一切都取决于你想知道什么。环境分为三大类:

  • Build: This is the environment in which the program is compiled.
  • Host: This is the environment in which the program is being run.
  • Target: In case of code-generation tools (such as compilers), this is where the generated code will run.
  • Build:这是编译程序的环境。
  • 主机:这是程序运行的环境。
  • 目标:对于代码生成工具(例如编译器),这是生成代码将运行的地方。

If you are cross-compiling, the build and host environment can be completely different (this is common when building embedded applications, but not very common when building desktop/server apps), and you typically cannot run the compiled binary on the system used to compile it. Otherwise, the host environment must be compatible with the build environment: for example, building an application on XP which will run on Vista.

如果您是交叉编译,则构建和宿主环境可能完全不同(这在构建嵌入式应用程序时很常见,但在构建桌面/服务器应用程序时并不常见),并且您通常无法在过去使用的系统上运行已编译的二进制文件编译它。否则,宿主环境必须与构建环境兼容:例如,在 XP 上构建将在 Vista 上运行的应用程序。

C preprocessor macros can not be used to tell you the details of the host system (i.e. what you are running on); they can only tell you what the code was compiled for. In the windows case, the two most important macros are:

C 预处理器宏不能用于告诉您主机系统的详细信息(即您正在运行的系统);他们只能告诉你代码是为了什么而编译的。在 windows 的情况下,两个最重要的宏是:

  • _WIN32signifies that the Win32 API is available. It does nottell you which compiler you are using, in fact _WIN32 is defined both when using Cygwin's GCC and MinGW's GCC. So, do not use _WIN32 to figure out if you're being compiled with Visual Studio.
  • _MSC_VERtells you that you the the program is being compiled with Microsoft Visual C/C++. Well, almost. _MSC_VERis alsodefined when using Intel's C++ compiler which is intended to be a drop-in replacement for Visual C++.
  • _WIN32表示 Win32 API 可用。它并不能告诉你,你正在使用的编译器,实际上_WIN32定义都使用Cygwin的GCC和MinGW的GCC的时候。因此,不要使用 _WIN32 来判断您是否正在使用 Visual Studio 进行编译。
  • _MSC_VER告诉您程序正在使用 Microsoft Visual C/C++ 编译。嗯,差不多。_MSC_VER使用英特尔的C ++编译器,其意图是一个简易替换为Visual C ++时定义。

There are a bunch of other macros described in the Visual Studio documentation.

Visual Studio 文档中描述了许多其他宏。

If you want to know which exact version of Windows you are using, you'll have to use runtime functions such as GetVersion() (as described in other answers).

如果您想知道您使用的是哪个确切版本的 Windows,则必须使用运行时函数,例如 GetVersion()(如其他答案中所述)。

You might get more specific answers if you told us exactly what you want to check for.

如果您确切地告诉我们您想检查什么,您可能会得到更具体的答案。

回答by Mr.Ree

% touch foo.C ; g++ -dM -E foo.C

Will do a nice job of listing all the macros (#define's) automagically defined for you by your [machine specific] g++ compiler.

将很好地列出由您的[机器特定] g++ 编译器自动为您定义的所有宏(#define 的)。

There might be something similar for Microsoft's compilers...

微软的编译器可能有类似的东西......

回答by Mr.Ree

These three lines will help you with detection, first we or most of the predefined windows hints together into one OS_WIN macro definition:

这三行将帮助您进行检测,首先我们或大多数预定义的 windows 提示一起成为一个 OS_WIN 宏定义:

#if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
#define OS_WIN
#endif

Then you can check for it using the preprocessor ifdef:

然后你可以使用预处理器 ifdef 检查它:

#ifdef OS_WIN
//Windows specific stuff
#else
//Normal stuff
#endif

回答by Mat-e

This thing works in visual studio 2012, and other cgwin's g++ compiler. Cut and paste it around but this is generally as thin as it gets All it does is detect windows op systems. Just apply quantification: If not win Then *inux :D enjoy

这东西适用于 Visual Studio 2012 和其他 cgwin 的 g++ 编译器。剪切并粘贴它,但这通常很薄,它所做的只是检测 Windows 操作系统。只需应用量化:如果没有赢,那么 *inux :D 享受

#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
Using namespace std;


int main(){    
    char chCap;    int i = 0;
    const int MAX_BUFFER = 70; 
    char buffer[MAX_BUFFER];

    string cmd="ver";   
    FILE *stream = _popen(cmd.c_str(), "r");

    if (0 != stream){
        while (!feof(stream)){  
            //One way is here
            //chCap = fgetc(stream);
            //cout << chCap;
            //buffer[i++] = chCap;

            //This one seams better
            fgets(buffer, MAX_BUFFER, stream);      
        }
        _pclose(stream);
    }       
    cout << endl;
    cout << buffer << endl;

    //The op sys detection starts here
    string opSys(buffer);   //char array to string
    if("Microsoft" == opSys.substr(0,9)){
        cout << "You are in a Microsoft envornment " << endl;
    }
    system("pause");
    return 0;    
}

回答by user51241

If you're running MS Windows targeted code you can call GetVersion() or GetVersionEx() for more info, and to identify the variant of Windows you are running on.

如果您正在运行 MS Windows 目标代码,您可以调用 GetVersion() 或 GetVersionEx() 以获取更多信息,并确定您正在运行的 Windows 变体。

For more info scope out the MSDN info.

有关更多信息,请查看 MSDN 信息。

http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx

http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx

回答by Jerry

The links mentioned so far indicate information at compile time. You can set flags within those code segments at compile time.

到目前为止提到的链接表示编译时的信息。您可以在编译时在这些代码段中设置标志。

However, I think what you are asking is more along the lines of "Which version of windows am I running under?"not "Am I compiled to run under windows?" I hope that's a correct assumption.

但是,我认为您要问的更多是“我在哪个版本的 Windows 下运行?”而不是“我是否编译为在 Windows 下运行?” 我希望这是一个正确的假设。

Under C#, it is relatively simple. You can reference System.Environment.OSVersion then look under "Platform".

在C#下,比较简单。您可以参考 System.Environment.OSVersion 然后在“平台”下查看。

However, you are asking about C++. What compiler are you using? THis makes a big difference as to how you check for a version of the operating system, as there is no single standard for getting this information (that I've found).

但是,您正在询问 C++。你用的是什么编译器?这对于检查操作系统版本的方式有很大的不同,因为没有单一的标准来获取这些信息(我已经找到了)。

Under Visual C++, use Google to find info on GetVersion/GetVersionEx. Both will give you structures that contain information on the current version of Windows that the program is running under.

在 Visual C++ 下,使用 Google 查找有关 GetVersion/GetVersionEx 的信息。两者都将为您提供包含有关程序正在运行的当前 Windows 版本信息的结构。

回答by j_random_hacker

The MSVC++ compiler (not windows.h) defines _WIN32for allbuilds, so it is a safer macro to check. The MinGW gcc compiler does too. Any cross-compilation environment targeting Win32 shouldset this too.

MSVC++ 编译器(不是windows.h_WIN32所有构建定义,因此检查它是一个更安全的宏。MinGW gcc 编译器也可以。任何面向 Win32 的交叉编译环境也设置此项。

回答by jmucchiello

Actually I would go with the Environment. getenv() is a standard library function and so is probably the only potentially portable way to do this. The trick is figuring out what variables are unique to all OSes. Windows has ComSpec, appdata, Windir, systemroot and systemdrive which should be set. You could also strstr the path variable for WINDOWS or WINNT but that might not be accurate. I'm not Linux shell/Solaris/MacOS expert so someone else might be able to tell you what "standard" environment variables exist in those OSes. CygWin may cause you some issues, too.

其实我会和环境一起去。getenv() 是一个标准库函数,因此可能是唯一可能的可移植方法。诀窍是找出所有操作系统独有的变量。Windows 有应该设置的 ComSpec、appdata、Windir、systemroot 和 systemdrive。您还可以 strstr WINDOWS 或 WINNT 的路径变量,但这可能不准确。我不是 Linux shell/Solaris/MacOS 专家,所以其他人可能会告诉您这些操作系统中存在哪些“标准”环境变量。CygWin 也可能会给您带来一些问题。

回答by Tim Post

Macros such as the ones listed above will tell you if you program was compiledon (or rather, for) a Windows machine, notif it is runningon a windows machine.

上面列出的宏会告诉你你的程序是否是在(或者更确切地说,)Windows 机器上编译的,而不是它是否在 Windows 机器上运行

If you write something that is completely platform agnostic (i.e. it only handles opening / reading / processing / writing) file streams .. you will have to do some test like open a file that should exist if the computer is running Windows. If your program uses only standard stdio, math, etc.. this will be the case.

如果你写的东西完全与平台无关(即它只处理打开/读取/处理/写入)文件流..你将不得不做一些测试,比如打开一个应该存在的文件,如果计算机运行的是Windows。如果您的程序仅使用标准的 stdio、数学等。情况就是这样。

Otherwise, if your code contains Windows specific system calls, its simply not going to run on any other platform.

否则,如果您的代码包含特定于 Windows 的系统调用,则它根本不会在任何其他平台上运行。

You could write some macro like:

您可以编写一些宏,例如:

#define RUNNING_ON_WINDOWS ( ... some test )

Just don't use it for conditional compilation, i.e.:

只是不要将它用于条件编译,即:

if (RUNNING_ON_WINDOWS) {
  ... 
} else 
   printf("Windows Required\n");