C++源程序到可执行文件的过程
编译器将C++源文件编译成目标文件,主要包括以下9个阶段。
Phase 1
-
源文件读入内存中,源文件的所有字节对应到“基本的源代码字符集”中。另外,与操作系统相关的换行符被替换为标准的newline字符。“基本的源代码字符集”包含96个字符:
a) 5 whitespace characters (space, horizontal tab, vertical tab, form feed, new-line) b) 10 digit characters from '0' to '9' c) 52 letters from 'a' to 'z' and from 'A' to 'Z' d) 29 punctuation characters: _ { } [ ] # ( ) < > % : ; . ? * + - / ^ & | ~ ! = , \ " '
-
在源程序中,不能转换为“基本的源代码字符集”的字符,被转换为“universal character name(\u or \U)”
Phase 2
- 如果遇到反斜线紧跟着换行符,则将反斜线和换行符都删除掉,这样就将两行合并为一行。这个执行过程只执行一遍,所以如果有两个反斜线和两个换行符连在一起,不会将第二个反斜线删除掉。
Phase 3
-
源文件被分解为注释,一系列空白字符,和多种preprocessing tokens。这些preprocessing tokens包括:
a) header names such as <iostream> or "myfile.h" (only recognized after #include) b) identifiers c) preprocessing numbers d) character and string literals , including user-defined (since C++11) e) operators and punctuators (including alternative tokens), such as +, <<=, new, <%, ##, or and f) individual non-whitespace characters that do not fit in any other category
-
如果此时,双引号中的字符串与源程序中的字符串不同,将现在的字符串还原为原来的字符串。
- 每个注释被用一个空格字符代替。
Phase 4
- 预处理被执行
- 将每个被#include 引入的文件,迭代进行上述四个阶段,并且,加到该文件中。
- 所有的预处理符被从源代码中移除掉
Phase5
所有的字面字符串被转换为可执行文件字符集。
Phase6
所有的相邻的字符串被连接。
Phase7
编译发生:每个preprocessing tokens 被转换为tokens,进行句法和语义分析,转换为 translation unit。
Phase8
每个translation unit 被分析,得到需要例化得模板实例,包括显示例化得模板实例。模板的定义被定位,实例化需要例化得单元,得到实例单元。
Phase9
translation unit and instantiation unit and extern library 被链接到程序映像中,即得到可执行文件。