Why is my external variable not yet initialized?

I am compiling a shared library with two compilation units: globals.cppand stuff.cpp. The file globals.cppinitializes several external variables that are used in stuff.cpp. The problem I encountered is that the code in was stuff.cpprun before the code in globals.cppwas able to assign the value to external variables. For example, I see a bunch of values 0. This problem depends on which platform I compile / run the code on - some work, and some not.

How can this be solved? Can I force a start globals.cpp?

+5
source share
3 answers

You cannot (sequentially)

But you can get around this.

global.cpp

// If you have a global variable that has to be initial by a constructor
MyObj globalX; 

// Instead do this

MyObj& globalX() { static MyObj x; return x;}

. , , , . , , . , , .

+6
+2

, , . globals.cpp:

 // top of source file

 #include "myincludes.h"

 CSomeClass someObject(432);
 int global_x = 42;
 int global_y = InitY();

. ( , , , " " .)

( ) .

It is better to have a function that explicitly initializes your library. Perhaps you need the application to call this function at startup or the exported library functions to call it after initialization is detected. Then initialize your global variables.

In my team, code that runs before "main" (or "DllMain") is strictly prohibited. In other words, there are no global objects. There are no functions for init globals.

0
source

All Articles