c - 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);
^
有什么提示吗?
解决方案
如果您查看翻译阶段,您会发现执行预处理器的阶段(阶段 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 characterPhase 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.
推荐阅读
- visual-studio - 与 Windows 上的 Visual Studio 配对时,iOS 构建失败并出现错误 MT0018
- google-cloud-platform - 如何在 GCP 上防止 DDOS 和加密通信
- three.js - 使用基于 Three.js 的 iTowns 上的 RayCasting 以 3D Tiles 格式提取 Z(以米为单位的高程)值的 3D 建筑文件的任何点
- html - 如何使用 NodeJS 执行 HTML 事件?
- javascript - 带有电子邮件链接的 Firebase 登录会删除 ActionCodeSettings URL 中的路径
- javascript - 如何使用 google drive api 将文件上传到 google drive?
- oauth-2.0 - Microsoft Power Automate 令牌不刷新
- c# - Identity Server 4 - MVC 客户端的 OpenIdConnect 处理程序中缺少角色声明
- python - 字符串重新定位
- heroku - Heroku:如何在部署期间在 Heroku 中的 python 应用程序上运行 npm build?