I have one translation unit with my main()
function and another TU without main. Suppose even that I only control the second one and can't touch the first one.
Now, for reasons I will not go into, I want to be able to run some code before main()
runs. I know this can be done by initializing a global variable with a function call, but I want to hide this - with as little use of macros as possible (dare I say no use of macros? probably impossible, there's no proper static block in C++)
What would be an elegant, or shall we say, not-very-ugly way of doing this? To be more clear, I'm looking for something which would provide this functionality for use multiple times, not just something to get it to work once. I want it to be as close to:
// ... at global scope ...
static {
// my code here
}
PS: This question is related, but not the same, as this question about initializing static class members. It's also motivated by the wish to clearly disprove this claim it can't be done in C++.
Note: Yes, I know about the static initialization order fiasco, no need to remind me of it... and I'm not asking for something which bypasses it. Obviously running code statically requires some prudence.