unit testing - How do local static objects govern compilation in C++? -
i have been learning effective c++ , in 1 of guidelines meyer mentions if declare non-local static object in 1 translation unit definition in translation unit results in undefined behaviour. problem fixed writing function returns reference local static object.
my question that:
how local static objects govern compilation of various translation units?
how compiler know translation unit execute first?
and apologies if asked question in bit incorrect way. hope understood meant.
how local static objects govern compilation of various translation units?
it's storage durations , privacy.
static objects need persist duration of program execution. placed in different area of memory stack or heap. other translation units may have static objects. having compiler tag these items, linker can throw them same area of memory.
static objects need privacy. when other translation units use variable identifiers (of static objects in other modules), can't because variables private. may produce error or compiler may decide generate copy in other translation unit.
if want variable "global" within translation unit, not have other translation units see it, declare static.
how compiler know translation unit execute first?
translation units not executed. functions executed. functions executed in order specified program's logic, regardless of reside.
by definition in c++ language, main()
function executed first, regardless of lives or order of compilation or order of linking.
note: there other functions executed before main, such c++ environment setup , constructors of global objects. taken care of compiler , programmer doesn't see it.
edit 1:
there many discussions of how global instances of classes or structures initialized, , when initialized.
for example, constructor of global class may call cout
print something. in order make work, i/o streams need initialized before constructor called. cout
object needs initialized before global object.
there other interesting issues well, discussion broad answer.
Comments
Post a Comment