C 如何知道在编译过程中是否定义了宏?

C 如何知道在编译过程中是否定义了宏?,c,macros,C,Macros,让我们在代码的某些部分中说,宏已经定义。在编译过程中,我想了解它是否已经定义并正在使用。我该怎么做?有两种方法: #ifdef MACRO // ... (code here will only be compiled if macro is defined) #endif 或 如果您希望在某些内容已定义或未定义时停止编译,请使用C预处理器的指令。 该页中的示例: #ifdef __vax__ #error "Won't work on VAXen. See comments at ge

让我们在代码的某些部分中说,宏已经定义。在编译过程中,我想了解它是否已经定义并正在使用。我该怎么做?

有两种方法:

#ifdef MACRO
// ... (code here will only be compiled if macro is defined)
#endif


如果您希望在某些内容已定义或未定义时停止编译,请使用C预处理器的指令。 该页中的示例:

 #ifdef __vax__
 #error "Won't work on VAXen.  See comments at get_last_object."
 #endif
将导致该消息出现编译错误。

使用
\ifndef
指令检查并使用
\error
指令引发错误:

#ifndef A_MUST_HAVE_MACRO
#error "A must have macro not defined"
#endif

如果您使用的是gcc编译器,那么您可以通过使用-E选项来确定是否正在使用它(间接地说,如果定义了它)。gcc手册页说明如下:

我想其他编译器也会有类似的选择。尝试找到一个在预处理阶段(即宏被替换的阶段)后停止的选项。

“已定义”和“正在使用”是两个独立的概念。检查宏标识符的定义很简单,可以在编译时完成,但在编译时不可能检查代码库中的用法(或正确用法)。您所说的“正在使用”是什么意思?
#ifndef A_MUST_HAVE_MACRO
#error "A must have macro not defined"
#endif
   -E  Stop after the preprocessing stage; do not run the compiler proper.  
   The output is in the form of preprocessed source code, which is sent 
   to the standard output.  Input files which don't require preprocessing 
   are ignored.