有没有办法逃避 C 预处理器指令?
我想做的是让 C 预处理器输出 #ifdef
、#else
和 #endif
指令。也就是说,我想以某种方式“转义”指令,以便预处理器的输出包含指令,该指令是要在输出上运行的预处理器。
是否可以“转义”CPP 指令,以便它由预处理器输出,这样如果 CPP 输出本身要进行预处理,则转义指令的输出将是预处理器指令?
What I am trying to do is have the C preprocessor output #ifdef
, #else
, and #endif
directives. That is, I would like to somehow "escape" a directive so that the output of the preprocessor includes the directive were the preprocessor to run on the output.
Is it possible to "escape" a CPP directive so that it is outputted by the preprocessor such that the output of an escaped directive would be a preprocessor directive if the CPP output were to be itself preprocessed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Marcelo Cantos 的答案 在 GNU cpp 4.4.3 上为我工作:
A slight variant of Marcelo Cantos's answer works for me on GNU cpp 4.4.3:
编辑:以下答案似乎仅适用于早期版本的
cpp
。它在 4.2.1 和 4.3.2 之间的某个地方中断。gcc -E
和g++ -E
甚至更早中断。详情请参阅评论。这里有一个似乎有效的技巧:
您必须直接使用
cpp
,因为编译器会尝试立即使用预处理器输出,并且不知道如何处理未处理的指令。EDIT: The following answer only appears to work on earlier versions of
cpp
. It breaks somewhere between 4.2.1 and 4.3.2.gcc -E
andg++ -E
break even earlier. See comments for the details.Here's one trick that seems to work:
You'll have to use
cpp
directly, since a compiler will try to immediately consume the preprocessor output and won't know what to do with the unprocessed directives.另一个似乎有效的技巧是:
使用 GCC 的预处理器(版本 4.5.2)我得到:
出于某种原因,该技术与 Ilmari Karonen 的解决方案,但是这个对于符合现代标准的 C 预处理器来说,这可能不是问题。
Another trick that seems to work is:
With GCC's preprocessor (version 4.5.2) I get:
For some reason, this technique has the same leading space issue as Ilmari Karonen's solution, but this is probably not an issue with modern standards-conforming C preprocessors.