Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static, global and multiple translation units

This consists of three questions which are linked:

1) How exactly do you end up with multiple translation units? Surely all the source and header files would "join" together because otherwise you would end up with code calling code which isn't part of that "program". Isn't a translation unit the same as a program?

2) How do static objects/classes work with regards to multiple translation units? If several source files in different translation units include a header which would create an object (that had a static data member) would there be a separate static data member per translation unit?

3) Similar to question 2, do global variables get shared across multiple translation units (a bit like me suggesting they were separate programs- just compiled together???) or do global variables still act.... global across all translation units?

like image 634
user997112 Avatar asked Mar 06 '13 22:03

user997112


Video Answer


2 Answers

1) Each source file, together with it's included header files, is called a translation unit. It gets compiled into an object file. The linker then finally joins all object files into the final executable. (Simplified, but to give you a basic idea)

2) The linker will eliminate the copies.

3) Yes, see 2)

like image 122
Daniel Frey Avatar answered Oct 13 '22 00:10

Daniel Frey


  1. No, they each are compiled into an object file which are subsequently linked together.

  2. If the object is declared but not defined in the header, which is the better practice, then there will just be one object defined (assuming it is in fact defined in exactly one source file) and everyone who includes the header will have a way of programming with it.

    static objects in a source file that would otherwise be in what appears to be global scope will not be accessible outside that translation unit. Outside of any class or function, static limits scope to the translation unit.

  3. Non-statically-scoped objects, yes, they do.

like image 33
djechlin Avatar answered Oct 12 '22 23:10

djechlin