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].

  1. 物理源文件字符以实现定义的方式映射到基本源字符集(为行尾指示符引入换行符)如果必要的.[SNIP]
  2. 每个反斜杠字符 () 的实例后面紧跟一个换行符都会被删除,将物理源代码行拼接到形成逻辑源代码行.[SNIP]
  3. 源文件被分解为预处理标记 (2.5) 和空白字符序列(包括注释).[SNIP]
  4. 执行预处理指令,扩展宏调用,并执行 _Pragma 一元运算符表达式.[SNIP]
  5. 字符文字或字符串文字中的每个源字符集成员,以及每个转义序列和通用字符名称在字符文字或非原始字符串文字中,转换为执行字符集的相应成员;[SNIP]
  6. 连接相邻的字符串文字标记.
  7. 分隔标记的空白字符不再重要.每个预处理令牌都被转换为一个令牌.(2.7).这对生成的标记进行语法和语义分析,并翻译为翻译单元.[SNIP]
  8. 翻译后的翻译单元和实例化单元组合如下:[SNIP]
  9. 所有外部实体引用均已解析.链接库组件以满足对未在当前翻译.所有这样的翻译输出都被收集到一个程序映像,其中包含执行所需的信息执行环境.

[脚注]实现必须表现得好像这些单独的阶段发生了一样,尽管在实践中不同的阶段可能被折叠在一起.

[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.)

相关文章