static void __attribute ((constructor)) init_function(void)

I believe this is the “sanctioned” way to cause init_function to be run before anything else when a module is loaded using gcc (According to Uli Drepper’s “How to Write Shared Libraries” of Red Hat).
The back story is a bit involved but the bottom line is that I require this functionality using PGI (and I require it for any library not just shared libraries). What is the equivalent construct for this in .o files created with PGI 6.1? I tried just using the same thing but while it successfully compiles and links, at run time, it appears to have not effect. Under Gnu 3.4 it does work. In essence, I need a runtime constructor for a number of .o files themselves. (Some .o objects in question are C++ – for which I could use some sort of static object constructor – however most .o objects are not C++).
Thanks in advance for any help,
Evan

Hi Evan,

While we do not support the GNU extension “static void __attribute ((constructor)) init_function(void)” we do support the init (constructor) pragma "#pragma init " with 6.1 and static libraries. In the up coming 7.0 release, we’ll also support the init pragma with shared libraries as well as the fini (destructor) pragma.

Example using constructors with 6.1:

% cat foo.c
#ifdef __cplusplus
   extern "C" {
#endif
   void printf (char * , ...);
   void constructor()
   {
      printf("Constructor started\n");
   }
#ifdef __cplusplus
   }
#endif
int main()
{
   printf ("Hello from main\n");
}

#pragma init constructor
% pgcc -V6.1-7 foo.c -o foo.out
% foo.out
Constructor started
Hello from main

Example of using constructors and destructors with 7.0-1:

% cat bar.c
#ifdef __cplusplus
   extern "C" {
#endif
   void printf (char * , ...);
   void constructor()
   {
      printf("Constructor started\n");
   }
   void destructor() {
      printf("Destructor called.\n");
   }
#ifdef __cplusplus
   }
#endif
#pragma init constructor
#pragma fini destructor
#ifdef __cplusplus
   extern "C" {
#endif
int bar(int a)
{
    return a + 1;
}
#ifdef __cplusplus
   }
#endif
% cat main.c
#include <stdio.h>
int bar(int);

void main() {
   int a = 100;
   printf("a=%d\n", a);
   a = bar(a);
   printf("a=%d\n", a);
}
% pgcpp -fpic -c bar.c
% pgcpp -shared -o libbar.so bar.o
% pgcc main.c libbar.so -o main.out
main.c:
% main.out
Constructor started
a=100
a=101
Destructor called.
  • Mat