C++程序的编译阶段有哪些?
C++ 程序的编译阶段是否由标准规定?
Are the stages of compilation of a C++ program specified by the standard?
如果有,它们是什么?
如果没有,一个广泛使用的编译器的答案(我更喜欢 MSVS)会很棒.
If not, an answer for a widely-used compiler (I'd prefer MSVS) would be great.
我说的是预处理、标记化、解析等.它们的执行顺序是什么?它们具体做什么?
I'm talking about preprocessing, tokenization, parsing and such. What is the order in which they are executed and what do they do in particular?
我知道编译、链接和预处理的作用,我最感兴趣的是其他和顺序.当然,也欢迎对这些进行解释,因为我可能不是唯一对答案感兴趣的人.
I know what compilation, linking and preprocessing do, I'm mostly interested in the others and the order. Explanations for these are, of course, also welcomed since I might not be the only one interested in an answer.
推荐答案
C++ 程序的编译阶段是否由标准规定?
Are the stages of compilation of a C++ program specified by the standard?
是和否.
C++ 标准定义了 9 个翻译阶段".引用 N3242 草案 (10MBPDF),日期为 2011-02-28(在官方 C++11 标准发布之前),第 2.2 节:
The C++ standard defines 9 "phases of translation". Quoting from the N3242 draft (10MB PDF), dated 2011-02-28 (prior to the release of the official C++11 standard), section 2.2:
翻译语法规则之间的优先级由以下阶段指定[见脚注].
The precedence among the syntax rules of translation is specified by the following phases [see footnote].
- 物理源文件字符以实现定义的方式映射到基本源字符集(为行尾指示符引入换行符)如果必要的.[SNIP]
- 每个反斜杠字符 () 后面紧跟一个换行符的实例都被删除,将物理源行拼接为形成逻辑源代码行.[SNIP]
- 源文件被分解为预处理标记 (2.5) 和空白字符序列(包括注释).[SNIP]
- 执行预处理指令,扩展宏调用,并执行 _Pragma 一元运算符表达式.[SNIP]
- 字符文字或字符串文字中的每个源字符集成员,以及每个转义序列和通用字符名称在字符文字或非原始字符串文字中,转换为执行字符集的对应成员;[SNIP]
- 连接相邻的字符串文字标记.
- 分隔标记的空白字符不再重要.每个预处理令牌都被转换为一个令牌.(2.7).这结果标记在句法和语义上进行分析和翻译为翻译单元.[SNIP]
- 翻译的翻译单元和实例化单元的组合如下:[SNIP]
- 解析所有外部实体引用.链接库组件以满足对未定义的实体的外部引用当前翻译.所有这些翻译输出都被收集到一个包含执行所需信息的程序映像执行环境.
[footnote] 实现必须表现得好像这些单独的阶段发生一样,尽管在实践中不同的阶段可能会折叠在一起.
[footnote] Implementations must behave as if these separate phases occur, although in practice different phases might be folded together.
正如 [SNIP] 标记所示,我没有引用整个部分,只是足以让大家理解.
As indicated by the [SNIP] markers, I haven't quoted the entire section, just enough to get the idea across.
强调一下,编译器不需要遵循这个确切的模型,只要最终结果就像他们那样.
To emphasize, compilers are not required to follow this exact model, as long as the final result is as if they did.
阶段 1-6 或多或少对应于预处理器,7 阶段与您通常认为的编译相关,8 阶段处理模板,9 阶段对应链接.
Phases 1-6 correspond more or less to the preprocessor, 7 to what you might normally think of as compilation, 8 deals with templates, and 9 corresponds to linking.
(C 的翻译阶段类似,但省略了 #8.)
(C's translation phases are similar, but #8 is omitted.)
相关文章