Global objects in libs

O

Oystein Haare

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...
 
R

Rob Williscroft

Oystein Haare wrote in 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,162
Latest member
GertrudeMa
Top