At the top of some file in my program, outside all functions, I have these variables:
namespace {
int foo = foo_func();
}
int bar = bar_func();
As you know, foo is a variable local only to that file, but bar is accessible to every file.
…but question: When are the functions foo_func() and bar_func() actually run? Does this happen before main() runs, or possibly sometime later (say just before those values are actually needed)?
The language specification states that the initializing functions will be executed before any function from that translation unit is called or any object defined in that translation unit is accessed. So, in general case it really depends on how your definitions are spread across translation units.
The initialization is carried out in top-to-bottom order, so, given your order of definitions,
bar_funcshould see already initializedfoo, butfoo_funcshould see “uninitialized” (i.e. zero-initialized)bar.Note, that if your
mainresides in another translation unit, it means that the initialization does not have to happen beforemain(). Yet, if you attempt to accessfooorbarfrommain(or from anywhere else), that should guarantee that the initialization process is triggered for the entire translation unit that defined these variables.Also, if your initializers are constant expressions (
constexprfunctions), then the whole initialization can be performed statically, which typically means that the variables will begin their lifetimes in already initialized (compile-time initialized) states.