Linkers, Loaders & Executables
How does C++ run the constructors of global objects before main?
- AThe CPU finds constructors and runs them first automatically
- BThe compiler always copies every constructor into the first line of main
- CAddresses of functions that call the constructors are gathered into a table such as .init_array, and the start-up code calls them before main
Show answer and explanation
Answer: C. Addresses of functions that call the constructors are gathered into a table such as .init_array, and the start-up code calls them before main
The compiler generates a function that initializes each file's global objects and puts its address in a special section called .init_array. The linker merges every file's .init_array into one table, and the start-up code or dynamic linker calls the functions in it before main. Termination work is gathered in .fini_array. The order of initialization across files is unspecified, so code must not depend on it.
- A. The CPU has no notion of constructors.
- B. Objects in other files are unknown to main's file.
- C. Correct. The linker merges each file's table into one.