I am using a 3rd party API that overrides the memory management functions found in the C Runtime libraries. In order for everything to work properly, I must make a call to initialize the API before any memory allocations take place.
The project I am working on uses a static Factory object that is dynamically initialized before any of the code in the main file is executed.
How can I ensure that the API will be initialized before the static Factory object?
The C++ standard library runs into the same problem: it has to ensure that cin, cout, etc. are initialized before any code, including constructors for static objects, uses them. The trick that was invented for handling this situation can also solve yours. In a header file that gets included first in every translation unit (well, every translation unit that has static objects with dynamic initializers):
class init_library {
public:
init_library() { if (counter++ == 0) initilaize_the_library(); }
private:
static int counter;
};
static init_library i_library;
and in one translation unit you have to provide a definition of init_library::counter.
This will put a static object of type init_library in every translation unit that pulls in the header. Its initialization will happen before any other initialization in that same translation unit (because its #include directive came first -- don't forget that!), and the first time that one of these objects gets initialized, it will call the code to initialize the library. (Note that this code is not thread-safe; making it thread-safe is straightforward)
This is known as the "nifty counter trick".
You should move your static factory objects initilization to a static function and call that function after initializing 3rd party lib as a first thing in main.
Related
I want the global variable's initialization (#A) to be called before initialization of static field (#B).
Currently, some static fields are initialized before global variable.
GridUtil.h
class GridUtil{
static Vec4* bPtr_; //will be filled
static void initGridCalculationCache();
static class _init //helper class
{
public:
_init() {
static_iniAll();
}
} _initializer;
}
GridUtil.cpp
#include "GridUtil.h"
GridUtil::_init GridUtil::_initializer;// (Edit: This line is just added, thank Dietmar Kühl.)
Vec4 b[24]; //#A executed 3rd : No, this should be the first.
Vec4* GridUtil::bPtr_=b; //#B executed 1st
void GridUtil::initGridCalculationCache() {
//.... fill GridUtil::bPtr_ using complex computation //#C executed 2nd
}
Result
From debugging, the execution order of above code is:-
B->C->A
But I want :-
A->B->C
I noticed that if "Vec4" is replaced by "int", the execution order will be:-
A->B->C
The objective is to set value of elements in the array (bPtr_) using a static function (initGridCalculationCache) that would be called automatically (helped by class _init).
If it is not possible, what is a correct way to do it?
The four obvious solutions in order of preference are:
Do not have global or static member variables to start with! These tend to create a large amount of problems, doubly so in systems utilizing concurrency.
Use constexpr objects as these get initialized during compilation time. There are, obviously, some constraints on what can be done but the compiler would verify that objects are initialized in the proper order.
Within a translation unit objects with static live time are initialized from top to bottom. That is, using the proper order if variable definition may achieve the desired order. There is, however, no portable approach ordering varriable initialization across translation units.
When there are dependencies on initialization between objects from different translation units the correct order can be guaranteed using function local static objects to which a reference is returned: these will be constructed upon first access.
The order is rather simple, POD are initialized by copying them from the .DATA section of your binary to RAM. Classes are initialized at runtime by their ctor. Therefore POD will allways be initialized befor any class with a ctor as long as they are in the same static area. If you use DLL/SO everything gets funny.
The order of initialization is undefined. There are no guarantees for anything. If you explicitly need an special order, initialize your static vars in an init function.
The project is compiled into a dll to be injected into an executable
The project relies on an API which is initialized at the very beginning in main() like so:
int DLL_main()
{
TheApi::Initialize();
AnObject anObjectInstance;
//..
}
There is an object that is constructed with a class definition similar to this:
class AnObject()
{
AnObject();
~AnObject();
static ApiHelper apiHelperObject; //This object assists in making certain api features easier to use
}
//Inside AnObject.cpp
ApiHelper AnObject::apiHelperObject;
In the constructor of apiHelperObject, there are some API function calls
Upon injection of the dll, nothing happens (no error message as well) however,
when the static keyword is removed from apiHelperObject all works fine
The issue seems to be that the static member is being constructed before the API is initialized
It is not possible to call TheApi::Initialize() in apiHelperObject's constructor because there are multiple different api helper objects, and that would cause TheApi::Initialize() to be called more than once
And so the question is:
What is the best way of initializing the api before the static member object is constructed? Or, what is the best way to delay the construction of the static member?
Preferably, a pointer is not used as the syntax is not especially favored
Thank you
In ordinary standard C++ you can always delay the initialization of a static object by making it local to an accessor function.
Essentially that's a Meyers' singleton:
auto helper_object()
-> ApiHelper&
{
static ApiHelper the_object;
return the_object;
}
Here, in standard C++, the object is initialized the first time execution passes through the declaration.
But the C++ standard does not actively support dynamic libraries, much less DLL injection. So it's difficult to say how this is going to play out. Beware of threading issues.
In short, I would like a particular piece of static initialization to occur as close to the beginning of main()/DllMain() as possible. It would probably be acceptable for this to be a constructor called last during static initialization.
Since this will almost certainly be a compiler-specific implementation, I'm specifically looking to do this using the visual C++ compiler (VS 2010 and beyond). In the future I will probably need to do this in GCC and Clang, but that's not an immediate concern.
The long story is I have a object in a base library that is statically initialized and creates a thread in its constructor. This thread relies on other statically initialized objects in libraries that we don't control so it causes a race condition in static initialization. If I can pause or avoid creating the thread until all other static initialization is complete this should fix the problem (a simple Sleep(5000) avoids the issue, though that's not exactly a robust solution).
I could explicitly call an initialize function in our main() function, however this isn't ideal as we have 20+ binaries that use this library so every programmer would have to remember to run the initialization in every binary. I would prefer to push this responsibility to the compiler if possible.
The comment of Refugnic Eternium above is correct, and offers one solution.
The best solution is to have a function like this:
BOOL InitMyLib();
All functions in MyLib.dll, and all constructors, should fail until this has been called. That way you can ensure that programmers don't forget to call it.
Create an initializer class and then declare a static instance of it:
class MyInitializer
{
public:
MyInitializer ()
{
doInitStuffHere();
}
};
static MyInitializer myInit;
You can control when the static variable is initialized by using #pragma init_seg. For example, #pragma init_seg(lib).
Use #pragma init_seg to Control Static Construction (KB104248)
Hi, all!
I'm developing winForm app on visual C++ (managed code).
This app link native static library which contain block of code with static variable initialization:
Cls.h
class Cls
{
public:
static Cls* getInstance();
private:
static Cls _instance;
protected:
Cls(void);
};
Cls.cpp
#include "StdAfx.h"
#include "Cls.h"
Cls::Cls(void)
{
}
Cls Cls::_instance;
Cls* Cls::getInstance()
{
return &_instance;
}
I can link those library successfully, but when I try to use getInstance() method I get a run-time error before invoke main function of my app.
It's a third party library, so I cannot rebuild it or redefine Cls class on any other way.
App project uses /clr, entry point defined as main.
I tired to search a solution. I found that I must change entry point, but I don't know what value would be correct.
Please, help!
You're encountering the notorious "static initialisation order fiasco". When static objects are defined in two translation units, it's unspecified which is initialised first; so, if the constructor of one refers to the other, you could end up accessing it before it is initialised. The only guarantee is that they will all be initialised before main begins.
The best solution is to avoid static objects. In particular, the Singleton anti-pattern that you are using is rather tricky to get right in C++, and is generally more trouble than it's worth.
If you really want to do this, then you can work around the fiasco by defining the static object inside a function:
Cls* Cls::getInstance()
{
static Cls _instance;
return &_instance;
}
This has the disadvantage that it introduces a "destruction order fiasco" (where it might not be safe to access from the destructor of another static object), and that it might not be thread-safe in some compilers (although it should be in any that claims C++11 compliance). If construction is thread-safe, then there will be a (small) runtime cost for each access, which might be a problem if you have extreme performance issues.
UPDATE: I've just noticed that you say that this evil class is outside your control and can't be changed. In that case, your options are:
Get rid of this library and use something less insane, or
Be careful not to access any of its static data until main has begun; in particular, follow my advice above and avoid any static objects of your own.
Suppose I have have a Car.h which define a class called Car , and I have implementation Car.cpp which implement my class Car, for example my Car.cpp can be :
struct Helper { ... };
Helper helpers[] = { /* init code */ };
Car::Car() {}
char *Car::GetName() { .....}
What is the life time of the helpers array ?
Do I need say static Helper helpers[]; ?
If I have done some bad practices, please let me know.
Any variable declared/defined in global / namespace scope has a complete life time until the code ends.
If you want your Helper helpers[]; to be accessible only within Car.cpp then only you should declare it as static; otherwise let it be a global. In other words,
Helper helpers[]; // accessible everywhere if `extern`ed to the file
static Helper helpers[]; // accessible only in `Car.cpp`
Edit: As, #andrewdski suggested in comment below; you should make helpers[] as static variable since you are using it within this file; even though Helper is not visible outside. In C++, if 2 entirely different unit has same named global variables then compiler silently create a mess by referring them to the same memory location.
Objects defined at file scope are called Static Storage Duration objects.
In most situations you can think of them as being created before main() is entered and destroyed after main() is exited (there are exceptions but I would not worry about that).
The order of destruction of static storage duration variables is the reverse order of creation.
The order of creation within the same compilation unit (file) is the order they are declared.
Note: There is no guarantee about the order of creation of Static Storage Duration objects across different compilation units.