如何找出 cl.exe 的内置宏

2021-12-22 00:00:00 c macros visual-c++ c++ cl

有谁知道我如何找出 cl.exe 的内置/预定义宏?例如对于 gcc,以下命令行将列出所有编译器的内置宏

Does anyone know how could I find out which are cl.exe's builtin/predefined macros? For example for gcc the following command line will list all the compiler's builtin macros

gcc -dM -E - </dev/null

我对类似于 gcc 的询问实际编译器"的方式感兴趣.

I'm interested in a way similar to gcc's that is "ask the actual compiler".

谢谢

推荐答案

此方法确实相当于向编译器询问预定义宏的列表,但它使用未记录的功能并且仅提供部分列表.为了完整起见,我将其包含在此处.

This method does amount to asking the compiler for the list of predefined macros, but it uses undocumented features and provides only a partial list. I include it here for completeness.

Microsoft C/C++ 编译器允许使用/B1 和/Bx 命令行开关分别为 .c 和 .cpp 文件调用替代编译器前端.命令行界面模块 CL.exe 通过 MSC_CMD_FLAGS 环境变量将选项列表传递给替换编译器前端.此选项列表包括一些预定义宏的 -D 宏定义.

The Microsoft C/C++ compiler allows an alternative compiler front-end to be invoked using the /B1 and /Bx command line switches for .c and .cpp files respectively. The command-line interface module CL.exe passes a list of options to the replacement compiler front-end via the MSC_CMD_FLAGS environment variable. This list of options includes -D macro definitions for some of the predefined macros.

以下简单的替换编译器前端打印出传递给它的选项列表:

The following trivial replacement compiler front-end prints out the list of options passed to it:

/* MyC1.c */

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *p;

    if ((p = getenv("MSC_CMD_FLAGS")) != NULL)
        printf("MSC_CMD_FLAGS:
%s
", p);

    if ((p = getenv("MSC_IDE_FLAGS")) != NULL)
        printf("MSC_IDE_FLAGS:
%s
", p);

    return EXIT_FAILURE;
}

将其编译为名为MyC1.exe"的可执行文件,确保它在 PATH 中可见,并告诉 CL.exe 使用以下方法之一将其作为编译器前端调用:

Compile this to an executable named, for example, "MyC1.exe", ensure it is visible in the PATH and tell CL.exe to invoke it as the compiler front-end using one of the following:

cl /B1MyC1.exe AnyNameHere.c  
cl /BxMyC1.exe AnyNameHere.cpp  

根据需要包括其他命令行选项,以查看为该组选项预定义了哪些宏.

Include other command-line options as required to see which macros are predefined for that set of options.

在结果输出中查找 -D 选项.下面给出了一个示例列表.在实际输出中,列表将以空格分隔,每个宏定义都以 -D 开头,并且还存在其他选项.

In the resulting output look for the -D options. An example list is given below. In the actual output the list will be space-separated, with each macro definition preceded by -D, and other options also present.

_MSC_EXTENSIONS  
_INTEGRAL_MAX_BITS=64  
_MSC_VER=1600  
_MSC_FULL_VER=160030319  
_MSC_BUILD=1  
_WIN32  
_M_IX86=600  
_M_IX86_FP=0  
_MT  

此技术似乎包括大多数依赖于命令行选项的宏,但不包括那些始终定义的宏,例如 __FILE__ 和 __DATE__.

This technique seems to include most macros that depend on command-line options, but excludes those that are always defined such as __FILE__ and __DATE__.

相关文章