How to force initialize a static local variable to main?

Consider a couple of functions below:

double MYAPI foo(double x) { return x; } Register register_foo_([] { return reg(&foo, "foo", ...); // function name repeated used }); 

register_foo_ is a global variable initialized to dllmain , the constructor of which takes a lambda that repeatedly refers to the function name above it literally. It would be great if the registration code could move inside the function above to reduce the likelihood of an error. I tried:

 double MYAPI foo(double x) { static Register register_foo_([] { return reg(&foo, "foo", ...); // static local does not initialize before dllmain }); return x; } 

If the above code works, I can easily turn it into a macro that uses __FUNCNAME__ . Is there a way to force initialize the register_foo_ static local variable before dllmain?

+5
source share
4 answers

I assume you want to get a syntax similar to:

 DEFINE_FUNC(void, foo, (double x)) { return x; } 

... and a template is generated. It is very simple to do this if you brought Register over the function using the declaration:

 #define DEFINE_FUNC(Ret, name, args) \ Ret name args; \ Register register_##name##_([] { \ return reg(&name, #name, ...); \ }); \ Ret name args 
+1
source

Static variables local to the function (method) are initialized the first time they use the function in which they are located. (They are initialized to zero when the program loads, and then initialized โ€œcorrectlyโ€ through code when the function is first introduced.) See the answers to this question . Thus, the movement of this code you propose into a function changes the initialization semantics, and this will not work.

Your source code worked, so you apparently wanted it to move the code inside the function, so it was somehow similar in your mind - or the mind of the code reader - so you can see that your string is a constant name and a name The functions were correct. It is also possible that you can provide registration. And so you want to make DRY.

The traditional (and only) way to achieve this is to use a preprocessor macro that expands into the registration call and function header.

You suggested using the macro yourself - now expand the macro so that it not only generates a registration function, but also a function header.

+3
source

Executes a function before main() , not sure if it will work for dllmain() :

 #include <iostream> int func_before_main() { std::cout << "func_before_main()" << '\n'; // do before main stuff return 0; } const int dummy = func_before_main(); int main() { std::cout << "main()" << '\n'; } 

Output:

 func_before_main() main() 
+3
source

No no. This is your answer.

0
source

All Articles