order of extern initialization?

K

Kyle Kolander

I was looking over the C++ standard for this answer and didn't find it...
probably not looking in the right spots.
Here's a quick setup:

// sn.h
extern const std::string SOME_NAME;
// sn.cpp
const std::string SOME_NAME = "SomeName";
/* sn.cpp is compiled and linked into libSomeName.so */

// myClass.h
#include <sn.h>
....
std::string ary[1] = { SOME_NAME };
// myClass.cpp
....
string s1 = ary[0]; // "" -- empty string
string s2 = SOME_NAME; // "SomeName"

Is this expected behavior? What is the order of initialization of global
variables (ary) vs. an extern string defined in a source file that has
already been compiled and linked into a library? I admittedly have not
spent enough time working with extern and generally shy away from global
variables...

Thanks,
Kyle
 
V

Victor Bazarov

Kyle said:
I was looking over the C++ standard for this answer and didn't find it...
probably not looking in the right spots.
Here's a quick setup:

// sn.h
extern const std::string SOME_NAME;

'SOME_NAME' has external linkage.
// sn.cpp
const std::string SOME_NAME = "SomeName";

'SOME_NAME' has external linkage and static storage duration and
is dynamically initialised (since it's not a POD).
/* sn.cpp is compiled and linked into libSomeName.so */

// myClass.h
#include <sn.h>
...
std::string ary[1] = { SOME_NAME };

'ary' has static storage duration and is dynamically initialised.
// myClass.cpp
...
string s1 = ary[0]; // "" -- empty string
string s2 = SOME_NAME; // "SomeName"

Both 's1' and 's2' have static storage duration and are dynamically
initialised.
Is this expected behavior?

Yes, just like any other. The order of initialisation of objects with
static storage duration defined in different translation units is simply
_unspecified_.
What is the order of initialization of global
variables (ary) vs. an extern string defined in a source file that has
already been compiled and linked into a library?

There is no such thing as "a library" in the language definition. It
is all platform-specific.
I admittedly have not
spent enough time working with extern and generally shy away from global
variables...

Not a bad idea.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top