Search code examples
c++cinitializationarduinoavr-gcc

How can I perform pre-main initialization in C/C++ with avr-gcc?


In order to ensure that some initialization code runs before main (using Arduino/avr-gcc) I have code such as the following:

class Init {
public:
    Init() { initialize(); }
};

Init init;

Ideally I'd like to be able to simply write:

initialize();

but this doesn't compile...

Is there a less verbose way to achieve the same effect?

Note: the code is part of an Arduino sketch so the main function is automatically generated and cannot be modified (for example to call initialize before any other code).

Update: ideally the initialization would be performed in the setup function, but in this case there is other code depending on it which occurs before main.


Solution

  • You can use GCC's constructor attribute to ensure that it gets called before main():

    void Init(void) __attribute__((constructor));
    void Init(void) { /* code */ }  // This will always run before main()