Take the 2-minute tour ×

It seems pretty clear that it is supposed to set things up.

  1. When exactly does it run?
  2. Why are there two parentheses?
  3. Is __attribute__ a function? A macro? Syntax?
  4. Does this work in C? C++?
  5. Does the function it works with need to be static?
  6. When does __attribute__((destructor)) run?

Example in Objective C:

static void initialize_navigationBarImages() {
  navigationBarImages = [[NSMutableDictionary alloc] init];

static void destroy_navigationBarImages() {
  [navigationBarImages release];
share|improve this question
add comment

3 Answers

up vote 104 down vote accepted
  1. It's run when a shared library is loaded, typically during program startup.
  2. That's how all GCC attributes are; presumably to distinguish them from function calls.
  3. GCC-specific syntax.
  4. Yes.
  5. No.
  6. The destructor is run when the shared library is unloaded, typically at program exit.

So, the way the constructors and destructors work is that the shared object file contains special sections (.ctors and .dtors on ELF) which contain references to the functions marked with the constructor and destructor attributes, respectively. When the library is loaded/unloaded the dynamic loader program (ld.so or somesuch) checks whether such sections exist, and if so, calls the functions referenced therein.

Come to think of it, there is probably some similar magic in the normal static linker, so that the same code is run on startup/shutdown regardless if the user chooses static or dynamic linking.

share|improve this answer
The double brackets make them easy to "macro out" (#define __attribute__(x)). If you have multiple attributes, e.g., __attribute__((noreturn, weak)), it'd be hard to "macro out" if there were only one set of brackets. –  Chris Jester-Young Jan 13 '10 at 1:22
It isn't done with .init/.fini. (You can validly have multiple constructors and destructors in a single translation unit, nevermind multiple in a single library -- how would that work?) Instead, on platforms using ELF binary format (Linux, etc.), the constructors and destructors are referenced in the .ctors and .dtors sections of the header. True, in the old days, functions named init and fini would be run on dynamic library load and unload if they existed, but that's deprecated now, replaced by this better mechanism. –  ephemient Jan 13 '10 at 5:16
FYI: In the gcc online documents (gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html) it says the following under "constructor, destructor": "These attributes are not currently implemented for Objective-C." –  cheshirekow Aug 30 '10 at 13:49
@ChrisJester-Young: #define __attribute__(x, ...) would work well in that case, with no added complexity. –  jcayzac Nov 22 '12 at 4:28
@ChrisJester-Young variadic macros are a standard C99 feature, not a GNU extension. –  jcayzac Nov 22 '12 at 7:10
show 5 more comments

.init/.fini isn't deprecated. It's still part of the the ELF standard and I'd dare say it will be forever. Code in .init/.fini is run by the loader/runtime-linker when code is loaded/unloaded. I.e. on each ELF load (for example a shared library) code in .init will be run. It's still possible to use that mechanism to achieve about the same thing as with __attribute__((constructor))/((destructor)). It's old-school but it has some benefits.

.ctors/.dtors mechanism for example require support by system-rtl/loader/linker-script. This is far from certain to be available on all systems, for example deeply embedded systems where code executes on bare metal. I.e. even if __attribute__((constructor))/((destructor)) is supported by GCC, it's not certain it will run as it's up to the linker to organize it and to the loader (or in some cases, boot-code) to run it. To use .init/.fini instead, the easiest way is to use linker flags: -init & -fini (i.e. from GCC command line, syntax would be -Wl -init my_init -fini my_fini).

On system supporting both methods, one possible benefit is that code in .init is run before .ctors and code in .fini after .dtors. If order is relevant that's at least one crude but easy way to distinguish between init/exit functions.

A major drawback is that you can't easily have more than one _init and one _fini function per each loadable module and would probably have to fragment code in more .so than motivated. Another is that when using the linker method described above, one replaces the original _init and _fini default functions (provided by crti.o). This is where all sorts of initialization usually occur (on Linux this is where global variable assignment is initialized). A way around that is described here

Notice in the link above that a cascading to the original _init() is not needed as it's still in place. The call in the inline assembly however is x86-mnemonic and calling a function from assembly would look completely different for many other architectures (like ARM for example). I.e. code is not transparent.

.init/.fini and .ctors/.detors mechanisms are similar, but not quite. Code in .init/.fini runs "as is". I.e. you can have several functions in .init/.fini, but it is AFAIK syntactically difficult to put them there fully transparently in pure C without breaking up code in many small .so files.

.ctors/.dtors are differently organized than .init/.fini. .ctors/.dtors sections are both just tables with pointers to functions, and the "caller" is a system-provided loop that calls each function indirectly. I.e. the loop-caller can be architecture specific, but as it's part of the system (if it exists at all i.e.) it doesn't matter.

The following snippet adds new function pointers to the .ctors function array, principally the same way as __attribute__((constructor)) does (method can coexist with __attribute__((constructor))).

#define SECTION( S ) __attribute__ ((section ( S )))
void test(void) {
void (*funcptr)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;

One can also add the function pointers to a completely different self-invented section. A modified linker script and an additional function mimicking the loader .ctors/.dtors loop is needed in such case. But with it one can achieve better control over execution order, add in-argument and return code handling e.t.a. (In a C++ project for example, it would be useful if in need of something running before or after global constructors).

I'd prefer __attribute__((constructor))/((destructor)) where possible, it's a simple and elegant solution even it feels like cheating. For bare-metal coders like myself, this is just not always an option.

Some good reference in the book Linkers & loaders.

share|improve this answer
add comment

Excellent answer by @janneb, very useful. Just for completeness, here is a link to the related GCC docs.

I'm glad I stumbled onto this question, it just allowed me to eliminate two dozen lines of boilerplate code and redundant function calls for doing some library-wide initialization in my Objective-C framework.

NOTE: Although this syntax is specific to GCC, LLVM and Clang have been written to support it as well, and code compiled using Clang-LLVM seems to work just like GCC-compiled code.

share|improve this answer
Note that since clang's documentation chooses to not mention these two attributes, they may as well be gone in the next release. Or the one after that. By using them you should prepare for the eventuality. –  jcayzac Nov 22 '12 at 4:31
@quinn Taylor... your link doesn't work.. care to elaborate how / which lines you were able to eliminate? + (void) load, + (void) initialize amongst them? –  alex gray Nov 1 '13 at 13:45
add comment

Your Answer


