开发者

Is there a way to escape a C preprocessor directive?

What I am trying to do is have the C preprocessor output #ifdef, #else, and #endif directives. That is, I would like to somehow "escap开发者_StackOverflow社区e" 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?


A slight variant of Marcelo Cantos's answer works for me on GNU cpp 4.4.3:

#define HASH(x) x

...

HASH(#)ifdef __cplusplus
class foo { };
HASH(#)endif


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 and g++ -E break even earlier. See comments for the details.


Here's one trick that seems to work:

#define HASH() #

...

HASH()ifdef __cplusplus
class foo { };
HASH()endif

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.


Another trick that seems to work is:

#define EMPTY
EMPTY#ifdef

With GCC's preprocessor (version 4.5.2) I get:

 #ifdef

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜