简体   繁体   English

C中的#ifndef被忽略了吗?

[英]#ifndef in C being ignored?

I have a bit of code where I want to have logging only if DEBUG is defined. 我有一些代码,只有在定义了DEBUG时我才想记录。 So I though I might be able to replace a Token (here: "DEBUGLOG") with the comment string "//". 所以我虽然可以用注释字符串“//”替换令牌(这里:“DEBUGLOG”)。 But how to do? 但怎么办?

    #ifndef DEBUG
     #define DEBUGLOG //
    #endif

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

There is no definition of DEBUG somwhere else in the code. 代码中没有其他地方的DEBUG定义。 But my gcc compiles this line and the program itself executes the printf(); 但是我的gcc编译了这一行,程序本身执行了printf();

Why? 为什么?

I tried to include it in parantheses like this, but it gets an compile error: 我试图将它包含在像这样的parantheses中,但它得到一个编译错误:

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

This is the compiler message: 这是编译器消息:

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

Any hints? 任何提示?

If you look up the Phases of translation , you will find that the Phase where preprocessor is executed (Phase 4) is after the phase where comments are replaced by a white space character (Phase 3). 如果你看看了翻译的阶段 ,你会发现其中预处理器执行(第四阶段)的阶段是评论一个空格字符(第3阶段)更换阶段之后

Phase 3 第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 1)源文件被分解为注释,空白字符序列(空格,水平制表符,换行符,垂直制表符和换页符),以及预处理标记,如下所示
... ...
2) Each comment is replaced by one space character 2) 每个注释被一个空格字符替换

Phase 4 第4阶段
1) Preprocessor is executed. 1) 执行预处理器。

So in Phase 3 the line: 所以在第3阶段,这条线:

#define DEBUGLOG //

becomes: 变为:

#define DEBUGLOG 

And in Phase 4 the line: 在第4阶段,该行:

DEBUGLOG        printf("Debug String"\n);

becomes: 变为:

printf("Debug String"\n);

And that is why your printf is executed. 这就是你的printf被执行的原因。

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. 这是一个编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM