I have a static library . I had gone through most of questions on stack overflow but could not come to a proper conclusion
C++ static initialization order
I have following files
File is myNew.h
#include <cassert>
#include <stdio.h>
void* operator new(size_t sz);
class myNew {
public:
myNew() {
initialize();
}
static void* newPageCheck();
static bool val;
private:
static void initialize();
};
File myNew.c
#include "myNew.h"
static myNew myNewObj __attribute__ ((init_priority (80)));
bool myNew::val = false;
// overload default new operator
extern void* operator new(size_t sz) {
return myNew::newPageCheck();
}
void myNew::initialize() {
val = true;
}
void* myNew::newPageCheck() {
assert(val == true);
int i ;
return &i
}
File my_slib_new.h
#include <stdio.h>
class myFoo {
public:
myFoo() {
int *i = NULL;
i = new int ;
funS();
}
void funS();
};
File my_slib_new.cc
#include "my_slib_new.h"
static myFoo foo __attribute__ ((init_priority (2000)));
void myFoo::funS() {
int *i = new int;
}
File sample_open_new.cpp
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "my_slib_new.h"
int main () {
printf ("Your Program will run ... \n");
int status = open("./libSharedNew.so",0);
return 0;
}
I did following steps
Step 1: First created the the static library from myNew.cc
1) g++ -g -c -fPIC myNew.cc
2) ar rcs libStaticNew.a myNew.o
Step 2: Created shared library from my_slib_new.cc
3) g++ -g -c -fPIC my_slib_new.cc
4) g++ -shared -o libSharedNew.so my_slib_new.o
Step 3 :
5) gcc -Wall -o myTest sample_open_new.cpp -L . -lSharedNew -lStaticNew
When I run myTest I get following assertion error
Assertion `MyNew::val == true' failed is because the static global object
static myFoo foo attribute ((init_priority (2000))); gets initialized before static global object
static myNew myNewObj attribute ((init_priority (80)));
My requirement is I cannot change linStaticNew.a to sharedLibrary .libStaticNew.a as to remain static only
I tried to delay the loading of Shared library by using open system call in sample_open_new.cpp but it did not work.
Is there is any way we can delay the loading of shared library libSharedNew.so , the idea is the static global object static myNew myNewObj attribute ((init_priority (80))); should be initialized first before static global myFoo object
or is there any we can specify the static global object of Static Library libStaticNew.a should be initialized first