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?
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)
No, they each are compiled into an object file which are subsequently linked together.
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.
Non-statically-scoped objects, yes, they do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With