gpt4 book ai didi

c - C 中的#ifndef 被忽略了吗?

转载 作者:行者123 更新时间:2023-12-01 13:17:38 25 4
gpt4 key购买 nike

我有一些代码,我只想在定义了 DEBUG 的情况下进行日志记录。所以我虽然可以用注释字符串“//”替换 token (这里:“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);
^

有什么提示吗?

最佳答案

如果您查找 Phases of translation ,您会发现执行预处理器的阶段(阶段 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.

所以在第 3 阶段,行:

#define DEBUGLOG //

变成:

#define DEBUGLOG 

在第 4 阶段,行:

DEBUGLOG        printf("Debug String"\n);

变成:

printf("Debug String"\n);

这就是执行 printf 的原因。

当你给它加上引号 ("//") 时,那一行变成:

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

引号 ("") 不会被删除。这是编译器错误。

关于c - C 中的#ifndef 被忽略了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53237899/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com