#pragma init and #pragma fini using gcc compiler o

2020-07-05 07:00发布

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 statements?

标签: c gcc pragma
3条回答
祖国的老花朵
2楼-- · 2020-07-05 07:21

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

查看更多
对你真心纯属浪费
3楼-- · 2020-07-05 07:35

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
}
查看更多
Root(大扎)
4楼-- · 2020-07-05 07:43

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

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

There's also a corresponding destructor attribute.

查看更多
登录 后发表回答