0

I want to create a program that reads a static library using dlfcn.h, in Main.c, there will be a variable called a which is global, and I want to access it through the library using extern int a and using it in a function, but at the same time do this and execute it, dlerror returns a non-null value, an error.

Main.c

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

int a = 37;

int main(){
  void *lib = dlopen("./libA.so", RTLD_NOW);
  if(dlerror() != NULL){
    printf("Error loading library.\n");
    return -1;
  }
  void (*f)() = dlsym(lib, "fun");
  dlclose(lib);
  return 0;
}

Lib.c

#include <stdio.h>

extern int a;

void fun(){
  printf("%i\n", a);
}

I tryed to use -fPIC argument in gcc but it doesn't works. De

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • You can bridge from the dynamic library into whatever loads it via functions, but I'm not sure you can bridge a global in some arbitrary executable into a library which has never heard of such an executable. Maybe you need an intermediate library to manage setting(s) like this, then both the loaded library and your main executable can use the same library, and by extension, value. – tadman Apr 19 '23 at 21:07
  • 1
    Perhaps if you actually printed what `dlerror()` returns, the actual error message, you'd have a better idea of what the problem is? – Sam Varshavchik Apr 19 '23 at 21:12
  • 2
    Any reason you can't make `fun` take an `int *` and send the address in from `main`? – wkz Apr 19 '23 at 21:12
  • 1
    The docs say "Any global symbols in the executable that were placed into its dynamic symbol table by ld(1) can also be used to resolve references in a dynamically loaded shared object." So I expect what you are trying to do to work -- or at least, to be work*able*. – John Bollinger Apr 19 '23 at 21:13

0 Answers0