I’m working (in Microsoft Visual C++ 2005.) on some tools for a large MMORPG that my company is developing. One thing I’m working on is a tool that scans over the codebase, finds various “magic” tokens in the code, parses the marked code, and auto-generates various snippets of code. (For instance, something that automaticaly finds enums and generates arrays of strings, to make enum-to-string conversion automatic).
Anyhow, I find myself with some snippets of code that I need to force-run at game startup time. I’m trying to come up with some way to do that forcing without any actual call being made in some global init() function.
Now, the code is mostly in C, but we have some C++, so I figured I could do something tricky with C++ initializers by declaring a class whose constructor takes a function pointer as one of its arguments, and then defining a single dummy member of that class at file scope with its argument being the function I want to have executed. So at code startup time, all global objects will be constructed, and presto, my code will be run.
Now, that works fine when I put it into a source file, compile that file into a project, and run the project. BUT, when I put it into a source file, compile that file into a library, and link the library into the project, it does NOT work, presumably because the linker strips out what it views as an unneeded variable.
So, I’m looking for two things:
(1) A different way to force code to run at startup time, one that can ideally be done entirely within a single file. That is, in foo.c, I put:
int myFunc()
{
gSomeVariable++;
}
AUTO_RUN(myFunc);
and presto, myFunc gets run at startup time
or
(2) A way to force a specific variable, or alternatively all the functions and variables in a single file, to get linked even if the linker thinks they are not being used.
Thanks