From: Carlos Pinto Coelho (cfspc_at_[hidden])
Date: 2002-04-02 09:26:59
Is there a way to force the initialization of a global
object that is defined in a library without having to
access its members?
I have a class registrar:
// file registrar.hpp
enroll(std::string const& name)
static void add_entry(std::string const& name);
static std::size_t num_entries();
static registrar_map& entries();
And I wish to "enroll" clients by instantiating
the inner class enroll:
// file: registrar_client.cpp
I am then testing the number of enrolled elements
std::cout << registrar::num_entries() << std::endl;
If I compile registrar_client.cpp, registrar.cpp and main.cpp together
the number of enrolled elements comes out ok. However, if
I compile the register_client.cpp in a separate library
and link it with the remaining code, the number of
enrolled elements comes out wrong.
I put a breakpoint in registar::add_entry and it is not
being called which seems to mean that the global
enroll_foo is not being initialized when it is in the
library. I have seen this behaviour in gcc-3.0.1,
metrowerks c++ codewarrior 7.0, and msvc 6.0 sp5.
Is there a way to force the initialization
of these global variables without having to
access them explicitly from main? Note that
the purpose of having the mechanism in the first
place was to avoid having a central file knowing
all the clients.
I have also tried making enroll foo a static
member of a static function in a class in
registrar_client.cpp but it did not work either.
Thanks in advance,
Carlos Pinto Coelho
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk