Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translation unit in C and C++

Tags:

c++

c

Is there a difference between what a translation unit is in C++ and 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?

like image 501
user103214 Avatar asked Dec 01 '11 13:12

user103214


3 Answers

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. If the source file #includes other files the text of those files gets included in the translation unit by the preprocessor. There is no difference between C and C++ on this matter.

like image 137
R. Martinho Fernandes Avatar answered Oct 13 '22 13:10

R. Martinho Fernandes


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

That's the translation unit.

like image 21
Bartek Banachewicz Avatar answered Oct 13 '22 11:10

Bartek Banachewicz


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

like image 37
James Kanze Avatar answered Oct 13 '22 13:10

James Kanze