Linkers, Loaders & Executables

How does C++ run the constructors of global objects before main?

  1. AThe CPU finds constructors and runs them first automatically
  2. BThe compiler always copies every constructor into the first line of main
  3. 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.
Practice this topic Back to topic

More Linkers, Loaders & Executables questions

  1. Which statement is correct about the object file (.o) a compiler produces from one source file?
  2. What is the main role of a linker?
  3. Which describes the symbol resolution a linker performs?
  4. Which describes the relocation a linker performs?
  5. Linking a C program gives "undefined reference to `foo'". What is the most likely cause?