首页 > 解决方案 > C中的#ifndef被忽略?

问题描述

我有一些代码,只有在定义了 DEBUG 的情况下才希望进行日志记录。所以我虽然可以用注释字符串“//”替换令牌(这里:“DEBUGLOG”)。但是怎么办?

    #ifndef DEBUG
     #define DEBUGLOG //
    #endif

[...] 
    DEBUGLOG        printf("Debug String"\n);
[...]

代码中的其他地方没有 DEBUG 的定义。但是我的 gcc 编译了这一行,程序本身执行 printf();

为什么?

我试图将它包含在这样的括号中,但它得到一个编译错误:

#ifndef DEBUG
 #define DEBUGLOG "//"
#endif

这是编译器消息:

beispiel.c:45:10: error: expected ‘;’ before ‘printf’
 DEBUGLOG printf("Debug String"\n);
          ^

有什么提示吗?

标签: cconditional-compilation

解决方案


如果您查看翻译阶段,您会发现执行预处理器的阶段(阶段 4)注释被替换为空白字符的阶段(阶段 3)之后。

Phase 3
1) The source file is decomposed into comments, sequences of whitespace characters (space, horizontal tab, new-line, vertical tab, and form-feed), and preprocessing tokens, which are the following
...
2) Each comment is replaced by one space character

Phase 4
1) Preprocessor is executed.

So in Phase 3 the line:

#define DEBUGLOG //

becomes:

#define DEBUGLOG 

And in Phase 4 the line:

DEBUGLOG        printf("Debug String"\n);

becomes:

printf("Debug String"\n);

And that is why your printf is executed.

And when you put it quotes ("//"), that line becomes:

"//"   printf("Debug String"\n);

The quotes ("") will not be removed. And this is a compiler error.


推荐阅读