Deprecated CALL_ON_[UN]LOAD pragmas

Q: I'm trying to build an old project that used the CALL_ON_LOAD and CALL_ON_UNLOAD pragmas and I'm getting warnings that these pragmas are deprecated and that I should use constructor and destructor attributes instead. What are constructor and destructor attributes?

A: The CALL_ON_LOAD and CALL_ON_UNLOAD #pragmas were added to GCC by Apple prior to the release of Mac OS X 10.0. They were used to specify routines to be called when a dynamic library was loaded or unloaded. They have now been deprecated and replaced by the constructor and destructor function attributes. A function with the constructor attribute is called when a dynamic library is loaded. Similarly, a function with the destructor attribute is called when a dynamic library is unloaded. When the constructor or destructor function is called, the return value of the function is ignored, and any parameters of the function are undefined. Note: This is a syntactical change for the compiler only; the pragmas and the attributes generate binary compatible code.

The constructor and destructor attributes are supported by gcc as of version 2.5.

Listing 1: Using #pragmas (deprecated, don't use)

// (deprecated, don't use)
#pragma CALL_ON_LOAD my_mod_init_func
static void my_mod_init_func(void)
{
    /* do my init stuff */
}

#pragma CALL_ON_UNLOAD my_mod_term_func
static void my_mod_term_func(void)
{
    /* do my termination stuff */
}

Listing 2: Using constructor and destructor attributes

void MyInitFunc(void) __attribute__ ((constructor))
{
    /* do my init stuff */
}

void MyTermFunc(void) __attribute__ ((destructor))
{
    /* do my termination stuff */
}

Note: When this code is built with gcc 4.0 you will get an error: attributes are not allowed on function-definitions. To correctly use function attributes with gcc 4.0 you have to put them on the function declarations:

Listing 3: Using constructor and destructor attributes with gcc 4.0

extern void MyInitFunc(void) __attribute__ ((constructor));
extern void MyTermFunc(void) __attribute__ ((destructor));

void MyInitFunc(void)
{
    /* do my init stuff */
}

void MyTermFunc(void)
{
    /* do my termination stuff */
}

Document Revision History

DateNotes
2006-01-10 
2005-08-10Adding gcc 4.0 information
2005-07-05Replace deprecated CALL_ON_[UN]LOAD pragmas with constructor [destructor] function attributes.

Posted: 2006-01-10


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.