如何在 C 预处理器中生成错误或警告?
我有一个必须仅在调试模式下编译的程序。 (测试目的)
如何让预处理器阻止在 RELEASE 模式下进行编译?
I have a program that must be compiled only in DEBUG mode. (testing purpose)
How can I have the preprocessor prevent compilation in RELEASE mode?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
放置在任何地方:
供参考:诊断
Place anywhere:
For reference: Diagnostics
C 提供了
#error
语句,并且大多数编译器都添加了#warning
语句。 gcc 文档建议引用该消息。C provide a
#error
statement, and most compilers add a#warning
statement. The gcc documentation recommends to quote the message.也许是更复杂的东西,但它只是以前解决方案的复制和粘贴。 :-)
PS 还有另一种方法来生成警告。
创建一个未引用的标签,例如
并且不引用它。在编译过程中,你会收到类似的警告
Maybe something more sofisticated, but it is only copy&paste of previous solutions. :-)
P.S. There is also another way how to generate a warning.
Create an unreferenced label like
and don't reference it. During compilation, you will get a warning like
您可以为此使用
error
指令。如果未定义DEBUG
,以下代码将在编译时抛出错误:You can use a
error
directive for that. The following code will throw an error at compile time ifDEBUG
is not defined:如果您只是想报告错误:
适用于大多数编译器。
If you simply want to report an error:
will work with most compilers.
对于 GCC 和 Clang(可能还有任何支持 _Pragma 功能的编译器),您可以定义一个宏:
您可以使用此宏进行临时 hack,例如绕过同事尚未编写的代码,以确保一旦您想要向公众发布版本,您就不会忘记修复它。要么
或者
For GCC and Clang (and probably any compiler that supports the _Pragma feature) you can define a macro:
You can use this macro for temporary hacks, for example to get around code that a co-worker hasn't written yet, to make sure you don't forget to fix it once you want to release a build to the public. Either
or
在Code::Blocks中,如果你不需要Release模式,可以删除Release模式。为此,请单击“项目”菜单,选择“属性...”,然后在“构建目标”选项卡中单击“发布”,然后单击“删除”按钮。删除Release模式仅适用于当前项目,因此您仍然可以在其他项目中使用它。
否则,如果你确实想使用预处理器,你可以这样做:
In Code::Blocks, if you don't want the Release mode, you can delete the Release mode. To do this, click on the Project menu, select Properties..., and in the Build targets tab you can click on Release and then click on the Delete button. Deleting the Release mode only does it for the current project, so you can still use it in other projects.
Otherwise, if you really want to use the preprocessor, you can do this: