Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does __attribute__((constructor)) work?

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:

__attribute__((constructor)) static void initialize_navigationBarImages() {   navigationBarImages = [[NSMutableDictionary alloc] init]; }  __attribute__((destructor)) static void destroy_navigationBarImages() {   [navigationBarImages release]; } 
like image 943
Casebash Avatar asked Jan 12 '10 22:01

Casebash


People also ask

How does attribute constructor work?

The constructor attribute causes the function to be called automatically before execution enters main () . Similarly, the destructor attribute causes the function to be called automatically after main () has completed or exit () has been called.

How to use__ attribute__ in C?

The __attribute__ directive is used to decorate a code declaration in C, C++ and Objective-C programming languages. This gives the declared code additional attributes that would help the compiler incorporate optimizations or elicit useful warnings to the consumer of that code.

What is constructor C++?

A constructor is a member function with the same name as its class. For example: class X { public: X(); // constructor for class X }; Constructors are used to create, and can initialize, objects of their class type.


1 Answers

  1. It runs 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, this works in C and C++.
  5. No, the function does not need to be static.
  6. The destructor runs 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.

like image 171
janneb Avatar answered Oct 08 '22 04:10

janneb