C预处理器是否首先评论或扩展宏? [英] Does the C preprocessor strip comments or expand macros first?

查看:188
本文介绍了C预处理器是否首先评论或扩展宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个(可怕的,可怕的,没有好的,非常糟糕的)代码结构:

  #define foo /注释掉调试代码

//错误格式化以不掩盖点
if(a)
foo(a);
bar(a);

我看到两个编译器的预处理器对此代码产生不同的结果:

  if(a)
bar(a);

  if(a)
;
bar(a);

显然,这对于可移植代码库来说是一件坏事。



我的问题:预处理器应该怎么做?不幸的是,原来的 .sourceforge.net / c_html / c.htmlrel =nofollow noreferrer> ANSI C规范明确排除第4节中的任何预处理器功能(本规范仅描述C语言,库或预处理器。)。



C99规范处理这个明确性,虽然。在翻译阶段中,单个空格替换了注释,它发生在预处理指令解析之前。 (详见第6.10节)。



VC ++ GNU C Compiler 都遵循这个范例 - 其他编译器可能不符合规定,如果它们是旧的,但如果它是C99兼容,你应该是安全的。


Consider this (horrible, terrible, no good, very bad) code structure:

#define foo(x) // commented out debugging code

// Misformatted to not obscure the point
if (a)
foo(a);
bar(a);

I've seen two compilers' preprocessors generate different results on this code:

if (a)
bar(a);

and

if (a)
;
bar(a);

Obviously, this is a bad thing for a portable code base.

My question: What is the preprocessor supposed to do with this? Elide comments first, or expand macros first?

解决方案

Unfortunately, the original ANSI C Specification specifically excludes any Preprocessor features in section 4 ("This specification describes only the C language. It makes no provision for either the library or the preprocessor.").

The C99 specification handles this explicity, though. The comments are replaced with a single space in the "translation phase", which happens prior to the Preprocessing directive parsing. (Section 6.10 for details).

VC++ and the GNU C Compiler both follow this paradigm - other compilers may not be compliant if they're older, but if it's C99 compliant, you should be safe.

这篇关于C预处理器是否首先评论或扩展宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆