如何知道编译期间是否定义了宏?

时间:2012-05-11 04:54:19

标签: c macros

让我们在代码的某些部分说明已经定义了一个宏。在编译期间,我想知道它是否已被定义并正在使用。我怎么能这样做?

4 个答案:

答案 0 :(得分:3)

检查#ifndef指令并使用#error指令抛出错误:

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

答案 1 :(得分:2)

有两种方法:

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

#if defined(MACRO)
// ...
#endif

答案 2 :(得分:2)

如果您正在使用gcc编译器,那么您可以使用-E选项查明它是否正被使用(并且间接地,如果已定义)。 gcc的手册页说明如下:

   -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.

我认为其他编译器会有类似的选择。尝试找到在预处理阶段(替换宏的地方)之后停止的选项。

答案 3 :(得分:1)

如果要查看是否定义了某些内容,请使用C预处理器的#error指令。 该页面的示例:

 #ifdef __vax__
 #error "Won't work on VAXen.  See comments at get_last_object."
 #endif

将导致该消息的编译错误。