是否有一种可移植的方法来打印来自 C 预处理器的消息?
我希望能够做类似
#print "C Preprocessor got here!"
调试之类的事情。最好/最便携的方法是什么?
I would like to be able to do something like
#print "C Preprocessor got here!"
for debugging purposes. What's the best / most portable way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
warning
指令可能是您能得到的最接近的指令,但它并不完全独立于平台:据我所知,它适用于除 MSVC 之外的大多数编译器,在 MSVC 上您必须使用
pragma< /代码> 指令:
The
warning
directive is probably the closest you'll get, but it's not entirely platform-independent:AFAIK this works on most compilers except MSVC, on which you'll have to use a
pragma
directive:MSVC 和 GCC。
Clang 最近开始添加支持,请参阅此处了解更多信息。
The following are supported by MSVC, and GCC.
Clang has begun adding support recently, see here for more.
大多数 C 编译器都会识别
#warning
指令,因此还有标准的“#error”指令,
虽然所有编译器都支持该指令,但它也会停止编译/预处理。
Most C compilers will recognize a
#warning
directive, soThere's also the standard '#error' directive,
While all compilers support that, it'll also stop the compilation/preprocessing.
您可能想尝试:
#pragma message("Hello World!")
You might want to try:
#pragma message("Hello World!")
效果很好。即使您使用 -Werror 也不会停止编译
works great. Also wouldn't stop compilation even if you use -Werror
另一种解决方案是使用注释加 shell 脚本来处理它们。这需要一定的纪律(或捕获拼写错误的 shell 脚本)。
例如,我添加格式为
//TODO
的注释,然后添加一个将所有注释收集到报告中的 shell 脚本。对于更复杂的用例,您可以尝试编写自己的简单预处理器。例如,您可以将源代码编辑为
*.c2
文件。简单的预处理器将读取源代码,查找//TODO
,并将printf("TODO ...")
写入输出*.c 文件。
Another solution is to use comments plus a shell script to process them. This takes some discipline (or a shell script which catches typos).
For example, I add comments formatted
//TODO
and then a shell script which collects all of them into a report.For more complex use cases, you can try to write your own simple preprocessor. For example, you could edit your sources as
*.c2
files. The simple preprocessor would read the source, look for//TODO
, and writeprintf("TODO ...")
into the output*.c
file.