如何在 msvc 预处理器中打印宏?

How to print macros in msvc preprocessor?

有没有办法使用 msvc 或 gcc 在预处理器文件中查看我的#defines?

这里有一些代码:

#include <iostream>

#define asdasdadda asdsad    

int main()
{
    #ifdef asdasdadda
        std::cout << "yes\n";
    #else
        std::cout << "no\n";
    #endif

    return 0;
}

我是这样用cl编译的:

$ cl main.cpp /C /P

这是预处理后的尾部 main.i:

#line 2 "main.cpp"




int main()
{

        std::cout << "yes\n";


#line 13 "main.cpp"

    return 0;
}

这是我的预期:

#line 2 "main.cpp"


#define asdasdadda asdsad

int main()
{

        std::cout << "yes\n";


#line 13 "main.cpp"

    return 0;
}

gcc 行为是相同的...

不要认为 MSVC 支持这个,但是对于 gcc 或 clang,使用 -dD 选项。有关详细信息,请参阅 Options Controlling the Preprocessor。具体来说:

-dCHARS

M Instead of the normal output, generate a list of #define directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no file foo.h, the command

touch foo.h; cpp -dM foo.h

will show all the predefined macros.

D Like M except in two respects: it does not include the predefined macros, and it outputs both the #define directives and the result of preprocessing. Both kinds of output go to the standard output file.

示例:

#define BLAH 1

int main()
{
#ifdef BLAH
      cout << "BLAH defined" << endl;
#else 
      cout << "undef" << i << endl;
#endif
}

g++ -E -dD q.cpp 产生:

# 1 "q.cpp" 2
#define BLAH 1

int main()
{

      cout << "BLAH defined" << endl;



}

有一个未记录的编译器开关 /d1PP,它将在预处理器输出中保留宏定义。如果你用 /P /d1PP 编译 Rado 的例子,你会得到以下输出文件:

#line 1 "q.cpp"
#define BLAH 1

int main()
{

      cout << "BLAH defined" << endl;


#line 10 "q.cpp"
}

请注意,此开关未记录在案。因此,它不受官方支持。它可能随时被删除,或者它的行为可能随时被改变。它可能有错误。使用风险自负等等等等