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?
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 entersmain ()
. Similarly, thedestructor
attribute causes the function to be called automatically aftermain ()
has completed orexit ()
has been called. Functions with these attributes are useful for initializing data that will be used implicitly during the execution of the program.
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).
I am guessing here but:
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;
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With