Oystein Haare wrote in news:pa****************************@online.no in
comp.lang.c++:
Note: This might be a bit off topic..
I want to create some global objects that register themselves with
another "manager"-class upon creation:
class SomeClass { ... };
// cpp:
SomeClass globalObj;
// other code
This works fine when I just compile and link everything at the same
time. However, if I compile the stuff with global objects and manager
as a static library (*.a) on linux, and try linking it with some
client code, it doesn't seem to work.
I guess it might be
because the symbols in the lib aren't actually resolved or handled at
all when I don't reference them in my client code, but how can I make
it work? Is there another way than to put this object creation into a
function?
This is all compiled with g++, lib created with 'ar'.
Hope I managed to describe my problem good enough...
Your problem is probably the way linkers work.
Usually they only link in things that are refrenced from
your non-library code.
In your library put something like:
// header code "your-lib.h"
struct link_this_library
{
static int no_use;
link_this_library()
};
// .cpp (TU) code
#include "your-lib.h"
int link_this_library::whatever = 0;
link_this_library::link_this_library()
{
++whatever;
}
// Non library code:
#include "your-lib.h"
link_this_library unused_;
int main()
{
}
The constructor call is needed as a Translation Unit (TU),
aka the code (.cpp) you put in your library, has to be
referenced so that you're guaranteed its initialization code
will be run.
unused_ will be constructed before main() is entered, so
everything should work.
HTH.
Rob.
--
http://www.victim-prime.dsl.pipex.com/