tags:

views:

436

answers:

3

I would like to build some code which calls some code on loadup of the shared library. I thought i would do it like this:

#pragma init(my_init)

static void my_init () {  
  //do-something
}

int add (int a,int b) {  
  return a+b; 
}

So when i build that code with

gcc -fPIC -g -c -Wall tt.c

It returns

gcc -fPIC -g -c -Wall tt.c 
tt.c:2: warning: ignoring #pragma init 
tt.c:4: warning: ‘my_init’ defined but not used

So its ignoring my #pragmas. I tried this in real code and my code aborted because a function hadn't been called in the pragma section because it was ignored.

How do i get gcc to use these #pragma init and fini statemets?

+6  A: 

pragmas are almost all compiler-specific. GCC doesn't implement init, but you can get the same effect using the constructor function attribute:

static void my_init () __attribute__((constructor))
{  
  //do-something
}

There's also a corresponding destructor attribute.

caf
exactly what i was looking for!
Josh
+1  A: 

Apparently #pragma init and #pragma fini are only supported by GCC for Solaris:

Michael Burr
A: 

Instead, use C++:

// init.cpp
namespace // an anonymous namespace
{
     class autoinit
     {
         public:
             ~autoinit(){ /* destruction code, if applicable */ }
         private:
             autoinit(){ /* content of myinit */ }
             static autoinit _instance;
     };

     autoinit 
     autoinit::_instance; // static instance forces static construction
}
Michael Aaron Safyan
He may require his code to be called before any static constructors are called in which case this may not work (initialization order can't be controlled and is not guaranteed) and is pretty much impossible to actually do in standard c++.
Grant Peters
@Grant, can you control the relative order of function declared with __attribute__((constructor))? If not, how is it any different? Besides, this method is portable across all C++ implementations, whereas the __attribute__((constructor)) syntax is GCC only.
Michael Aaron Safyan
@Michael, I believe the __attribute__((constructor)) syntax does guarantee that it is called before all other code. Additionally, it allows you to specify a priority for that constructor so if multiple are specified it knows what order to run them in. As to the portability, I was saying that having your code called before any static class constructors (i.e. controlling initialization) isn't possible via standard c++, there is no portable way of doing it. You have simply pointed out what I was saying already and your method still doesn't allow for the code to run before any static classes.
Grant Peters