Forcing global constructors to execute

Started by
21 comments, last by doynax 19 years, 5 months ago
Quote:Original post by Leadorn
Ive retested it with a totaly new empty console project and it calls the constructor on the static Test test object.

Yeah, with an empty project it works properly as I said earlier, but not with his example -- where the object is in a static link library.

Quote:Original post by Namethatnobodyelsetook
If I recall, making it static makes it initialize on first use. Why not just make it global and non-static?

Not true, see previous replies.
Advertisement
Thanks for the effort guys, but this isn't an optimization issue I think.
Furthermore I'm more or less stuck with the Intel C++ compiler for other reasons and as shown above it doesn't seem to work with ANY other compiler/linker either. Funny though that GCC and metroworks compilers seems to have realize that there exists a problem and provided solutions for it. I've looked at possible pragmas and __declspec's but none seems to do what I want.

The most promising seemed to be the #pragma init_seg, but I'm a bit confused on how to use it and I'm quite sure it can't be used to do what I need: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccelng/htm/pragm_14.asp
I can confirm that this problem exists with at least VC6.
We had to work around it, even for non trivial classes, by referencing dummy functions inside the static classes manually.

There's nothing strange about it though. The linker just reckons that since no one accesses the the class from the outside it can be safely removed since it doesn't seem to be used anyway.
It's not much of an issue since the one-in-a-million case where it happens to guess wrong can be easily worked around, the alternative would be to include a lot of unnecessary code just to be sure, which is much worse.

This topic is closed to new replies.

Advertisement