How do local static objects govern compilation of various translation units?
It's about the storage durations and privacy.
Static objects need to persist for the duration of the program execution. They are generally placed in a different area of memory than stack or heap. Other translation units may have static objects. By having the compiler tag these items, the linker can throw them all into the same area of memory.
Static objects need privacy. When other translation units use the variable identifiers (of static objects in other modules), they can't because the variables are private. This may produce an error or the compiler may decide to generate a copy in the other translation unit.
If you want a variable that is "global" within a translation unit, but not have other translation units see it, declare it as static.
How does the compiler know which translation unit to execute first?
Translation units are not executed. Functions are executed. Functions are executed in the order specified by the program's logic, regardless of where they reside.
By definition in the C++ language, the main()
function is executed first, regardless of where it lives or the order of compilation or the order of linking.
Note: There are other functions that are executed before main, such as C++ environment setup and constructors of global objects. This is taken care of by the compiler and the programmer usually doesn't see it.
Edit 1:
There are many discussions of how global instances of classes or structures are initialized, and when they are initialized.
For example, a constructor of a global class may call cout
to print something. In order to make this work, the I/O streams need to be initialized before this constructor is called. So now the cout
object needs to be initialized before a global object.
There are other interesting issues as well, but that discussion is to broad for this answer.