开发者

How does one force construction of a global object in a statically linked library? [MSVC9]

I have a global list of function pointers. This list should be populated at startup. Order is not important and there are no dependencies that would complicate static initialization. To facilitate this, I've written a class that adds a single entry to this list in its constructor, and scatter global instances of this class via a macro where necessary. One of the primary goals of t开发者_开发技巧his approach is to remove the need for explicitly referencing every instance of this class externally, instead allowing each file that needs to register something in the list to do it independently. Nice and clean.

However, when placing these objects in a static library, the linker discards (or rather never links in) these units because no code in them is explicitly referenced. Explicitly referencing symbols in the compilation units would be counterproductive, directly contradicting one of the main goals of the approach. For the same reason, /INCLUDE is not an acceptable option, and /OPT:NOREF is not actually related to this problem.

Metrowerks has a __declspec directive for it, GCC has -force_load, but I cannot find any equivalent for MSVC.


I think you want a #pragma optimize("", off) and #pragma optimize("", on) pair around these variable declarations. That will turn off the optimization which is discarding them.

Also remember preprocessor directives can't be part of macros. __pragma can be used for some things (and is designed specifically to be used in macros), but not everything, and the syntax is a little different. Not sure if it works with optimize.


If you don't want to #include anything, then this won't work, but if you can live with that, a common technique is to use a nifty-counter to call a function declared in the cpp file before main, which would then initialize any static objects in said file.

I've used this in projects that had a lot of objects that should go into factory. We had to have one file that #include each header that declared a class that must register itself in the factory. It's reasonably doable IMHO, as I strongly prefer writing source files as opposed to setting various linker/compiler options.

Another way (that doesn't seem to work via static libs, see comments) could be to declare something as __declspec(dllexport), which would force its inclusion (__declspec works in executables too).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜