简体   繁体   English

C和C ++中的翻译单元

[英]Translation unit in C and C++

Is there a difference between what a translation unit is in C++ and C? C ++和C中的翻译单元之间有区别吗?

In other posts, I read that a header and source file makes a translation unit, but can a source file alone be called a translation unit in C++ where it contains all the definitions in one file? 在其他帖子中,我读到标题和源文件构成了一个翻译单元,但是单独的源文件可以在C ++中被称为翻译单元,其中它包含一个文件中的所有定义吗?

A translation unit is not "a header and a source file". 翻译单元不是“标题和源文件”。 It could include a thousand header files (and a thousand source files too). 它可能包括一千个头文件(以及一千个源文件)。

A translation unit is simply what is commonly known as "a source file" or a ".cpp file" after being preprocessed. 翻译单元是预处理后通常称为“源文件”或“.cpp文件”的单元。 If the source file #include s other files the text of those files gets included in the translation unit by the preprocessor. 如果源文件#include s其他文件,则预处理器将这些文件的文本包含在翻译单元中。 There is no difference between C and C++ on this matter. 在这个问题上,C和C ++之间没有区别。

Header is added to the .cpp file on preprocessing, so the compilator is basically working on a big chunk of code, containing both .cpp and all of .h added by "#include". 在预处理时,标题被添加到.cpp文件中,因此编译器基本上处理大量代码,包含.cpp和“#include”添加的所有.h。

That's the translation unit. 那是翻译单位。

It depends on what you mean by “difference”. 这取决于你所说的“差异”。 Both C and C++ define it similarly: basically, everything that gets compiled when you compile a source file (thus, all of the included headers, expanded macros, etc.). C和C ++都类似地定义它:基本上,在编译源文件时编译的所有内容(因此,所有包含的头,扩展的宏等)。 But that's not the same thing in the two languages; 但这两种语言不一样; things like templates mean that translation units do behave differently in C++ than in C. (C++ has the one definition rule, for example.) 像模板这样的东西意味着翻译单元在C ++中的行为与在C中的行为不同。(例如,C ++有一个定义规则。)

A translation unit is actually what you get once the source and header files have passed through preprocessing (which expands the source using the header files) and precompilation. 翻译单元实际上是源文件和头文件通过预处理(使用头文件扩展源代码)和预编译后获得的。 The compiler uses the translation unit to produce the .obj files that you see in your compiler output directory. 编译器使用转换单元生成您在编译器输出目录中看到的.obj文件。

编译器看到的源文件集并作为一个单元进行翻译

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM