[Gc] GC and dynamic libraries

Joris van der Hoeven vdhoeven at texmacs.org
Thu Jun 10 04:08:44 PDT 2004


This may be a frequently asked question: do I need to do something special
in order to use GC in combination with dynamically loaded libraries?

Indeed, I am writing an interpreter which uses GC as its garbage collector,
and which should be able to dynamically load third party libraries using
an instruction from within the interpreter. I work under GNU/Linux
and used the commands

	g++ -fPIC -c -I/home/vdhoeven/mathemagix/src/include/ mmx-simple.cc -o mmx-simple.o
	g++ -lgc -fPIC -shared mmx-simple.o -o mmx-simple.so

in order to compile my .so. I also used the code below for
the dynamic linking from within the interpreter:

evaluator_rep::kw_use_2 () {
  // Input: (use_2, module_name, cont, ...)
  string name= as_string (V (car (rem)));
  string lib = string("mmx-"*name*".so");
  string rout= "init_" * name; // attention to mangling by C+
  char* _lib = as_charp (lib);
  char* _rout= as_charp (rout);

  void* handle= dlopen (_lib, RTLD_LAZY | RTLD_GLOBAL);
  if (handle == NULL) {
    error (car (trace), dlerror ());
    // cerr << "Dynamic library " << lib << " did not open\n";
  else {
    void* f= dlsym (handle, _rout);
    if (f == NULL) {
      error (car (trace), "Symbol " * rout * " not defined in " * lib);
    else {
      void (*init) (void)= (void (*) (void)) f;
      init ();
  cur= cadr (rem);
  rem= cons (VAL_NONE, cddr (rem));
  // Output: (cont, none, ...)
  trace= cdr (trace);

When doing so, I obtain a segmentation fault after a while.
When I statically link the same code, everything works fine.
So I probably used a wrong linking option or should I tell
the GC about dynamically linked libraries?

Thanks for your time, Joris

Joris van der Hoeven <vdhoeven at texmacs.org>
https://www.texmacs.org: GNU TeXmacs scientific text editor
https://www.math.u-psud.fr/~vdhoeven: personal homepage

More information about the Gc mailing list