help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

static template attribute cross plugins


From: oo_knulp_oo
Subject: static template attribute cross plugins
Date: 14 Jul 2005 06:38:41 -0700
User-agent: G2/0.2

Hi. I have a template that implements the singletone pattern,
and I use the same template cross different plugins. Now, the
static variabile is included in each plugin (shared object),
but I want it to be the same for the whole application.
The example:

####################### Makefile
all: lib1.so lib2.so main

lib1.so: obj1.o
        ld -g -shared -o lib1.so obj1.o

lib2.so: obj2.o
        ld -g -shared -o lib2.so obj2.o

obj1.o: obj1.c
        g++ -g -c obj1.c

obj2.o: obj2.c
        g++ -g -c obj2.c

main: main.o
        g++ -g -o main main.o -ldl

main.o: main.c
        g++ -g -c main.c
####################### tpl.h
template <class T>
class A {
  public:
    static A *get() {
      if (!singleton)
        singleton = new A();
      printf("get called\n");
      return singleton;
    }
  private:
    static A *singleton;

    A() {
       printf("singleton built\n");
    }
};

template <class T> A<T> *A<T>::singleton = NULL;
####################### obj1.c
#include <stdio.h>
#include "tpl.h"

using namespace std;

extern "C" void f1() {
  printf("f1()\n");
  A<int>::get();
  A<int>::get();
}

####################### obj2.c
#include <stdio.h>
#include "tpl.h"

using namespace std;

extern "C" void f2() {
  printf("f2()\n");
  A<int>::get();
  A<int>::get();
}

####################### main.c
#include <stdio.h>
#include <dlfcn.h>

void launch(char *name, char *lib) {
  void *handle;
  void (*f)();
  char *error;

  handle = dlopen(lib, RTLD_LAZY);
  if (!handle) {
    fprintf (stderr, "%s\n", dlerror());
    return;
  }

  dlerror();

  printf("looking for symbol\n");

  f = (void(*)())dlsym(handle, name);
  if ((error = dlerror()) != NULL)  {
    fprintf (stderr, "%s\n", error);
    return;
  }

  (*f)();
}

int main() {
  launch("f1", "lib1.so");
  launch("f2", "lib2.so");
}

####################### output
looking for symbol
f1()
singletone built
get called
get called
looking for symbol
f2()
singletone built
get called
get called

The problem is that the singleton is built two time
instead once cause the symbol is repeated twice:

# objdump --syms lib1.so |grep singleton
00001600  w    O .bss   00000004 _ZN1AIiE10singletonE
# objdump --syms lib2.so |grep singleton
00001600  w    O .bss   00000004 _ZN1AIiE10singletonE

How is possible to avoid this problem?



reply via email to

[Prev in Thread] Current Thread [Next in Thread]