Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a function immediately before main

Is is possible to register a function to be run immediately before main is entered? I know that all global objects are created before entering main, so I could put the code in the constructor of a global object, but that does not guarantee any particular order. What I would like to do is put some registration code into the constructor, but alas, I don't know what to put there :) I guess this is highly system-specific?

like image 339
fredoverflow Avatar asked Mar 07 '11 16:03

fredoverflow


3 Answers

If you're using gcc, you can use the constructor attribute on a function to have it called before main (see the documentation for more details).

constructor

destructor

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. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.

like image 156
Sylvain Defresne Avatar answered Oct 05 '22 11:10

Sylvain Defresne


Not sure this is exactly what you want... But it should do the job.

int main() {
  static int foo = registerSomething();
}

It's better to explicitly calls such registration functions, either in main or on first access (but first access init could pose issues if you're multithreaded).

like image 44
Erik Avatar answered Oct 05 '22 11:10

Erik


I am guessing here but:

  1. You want to register something in a different compilation unit
  2. You ran into a problem with the registration because the global variables in which you're saving registrations were not yet constructed.

C++ defines that a function-static is initialized sometime before it is first accessed, so you can work around it in the way shown below.

typedef std::map<std::string, std::string> RegistrationCache;

RegistrationCache& get_string_map()
{
    static RegistrationCache cache;
    return cache;
}

class Registration
{
    Registration(std::string name, std::string value)
    {
        get_string_map()[name] = value;
    }
};
like image 33
Dark Falcon Avatar answered Oct 05 '22 11:10

Dark Falcon