如何使预处理器在宏扩展结果中插入换行符?
使用 C/C++ 宏,可以很容易地自动生成长结构。例如,如果我希望一组方法永远不会抛出异常(对于 COM 公开的方法来说是必须的),我可以这样做:
#define BEGIN_COM_METHOD\
try{
#define END_COM_METHOD\
return S_OK;\
} catch( exception& ) {\
// set IErrorInfo here\
return E_FAIL;\
}
为了使此类宏易于管理,可以使用“\”字符使宏定义成为多行并且更具可读性。
问题是有时具有此类构造的代码将无法编译 - 某些内容不会按预期扩展,并且编译器将出现无效代码。编译器通常有“生成预处理文件”选项来向开发人员展示预处理结果。但在预处理后的文件中,宏被扩展为一行,结果几乎不可读。
是否可以使预处理器保留宏定义中存在的换行符?
With C/C++ macros it's quite easy to generated long constructs automatically. For example, if I want a huge set of methods to not ever throw exceptions (a must for COM-exposed methods) I can do something like this:
#define BEGIN_COM_METHOD\
try{
#define END_COM_METHOD\
return S_OK;\
} catch( exception& ) {\
// set IErrorInfo here\
return E_FAIL;\
}
to make such macros manageable one can use "\" character to make the macro definition multiline and more readable.
The problem is sometimes code with such constructs will not compile - something will not expand as expected and invalid code will be present to the compiler. Compiler usually have "generate preprocessed file" option to show the developer the preprocessing result. But in the preprocessed file the macro is expanded into one line and the result is barely readable.
Is it possible to make the preprocessor to keep the linebreaks present in the macro definition?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你做不到。替换文本一直到 #define 所在行的末尾为止,因此其中不会有换行符。如果您的编译问题并不常见,您可以在编译之前通过缩进或类似的方式运行预处理文件,这有助于您获得更具可读性的代码。
You can't do it. The replacement text is until the end of the line where it is
#define
d, so it will not have newlines in it. If your problems with compilation are infrequent, you could run the preprocessed file throughindent
or something like that before compiling when that happens to help you get more readable code.这是不可能的,因为
\
字符在第 2 阶段(在涉及预处理器之前)被删除。请参阅问题包含 8 个翻译阶段的海报C 语言 中的翻译阶段列表。This is not possible since the
\
characters are removed in phase 2, before the preprocessor is involved. See the question Poster with the 8 phases of translation in the C language for a list of the phases of translation.