3.6 __attribute__((constructor[(priority)])) function attribute

This attribute causes the function it is associated with to be called automatically before main() is entered.

Syntax

__attribute__((constructor[(priority)]))
Where priority is an optional integer value denoting the priority. A constructor with a low integer value runs before a constructor with a high integer value. A constructor with a priority runs before a constructor without a priority.
Priority values up to and including 100 are reserved for internal use. If you use these values, the compiler gives a warning.

Usage

You can use this attribute for start-up or initialization code.

Example

In the following example, the constructor functions are called before execution enters main(), in the order specified:
#include <stdio.h>
void my_constructor1(void) __attribute__((constructor));
void my_constructor2(void) __attribute__((constructor(102)));
void my_constructor3(void) __attribute__((constructor(103)));
void my_constructor1(void) /* This is the 3rd constructor */
{                        /* function to be called */
    printf("Called my_constructor1()\n");
}
void my_constructor2(void) /* This is the 1st constructor */
{                         /* function to be called */
    printf("Called my_constructor2()\n");
}
void my_constructor3(void) /* This is the 2nd constructor */
{                         /* function to be called */
    printf("Called my_constructor3()\n");
}
int main(void)
{
    printf("Called main()\n");
}

This example produces the following output:
Called my_constructor2()
Called my_constructor3()
Called my_constructor1()
Called main()
Non-ConfidentialPDF file icon PDF versionARM DUI0774E
Copyright © 2014-2016 ARM. All rights reserved.