0

First of all, I have seen this (<- a link), and it isn't working. I am using OS X.

a.c:

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

int global_var = 0x9262;

int main(void) {
  void *handle = dlopen("libb.so", RTLD_LAZY);
  void (*func)(void);
  char *err;
  if (handle == NULL) {
    fprintf(stderr, "%s\n", dlerror());
    return 1;
  }
  func = dlsym(handle, "func");
  if ((err = dlerror()) != NULL) {
    fprintf(stderr, "%s\n", err);
    return 2;
  }
  global_var = 0x9263;
  func();
  return -dlclose(handle) * 3;
}

b.c:

#include <stdio.h>

extern int global_var;

void func(void) {
  printf("0x%x\n", global_var);
}

Compiling and running:

$ gcc -shared -rdynamic -fpic -o liba.so a.c
$ gcc -shared -fpic -o libb.so -L. -la b.c
$ gcc -fpic -o a a.c
$ ./a
0x9262

Why doesn't it print 0x9263? I have tried many combinations of compiler flags, and none of them work.

Community
  • 1
  • 1
Adrian
  • 14,931
  • 9
  • 45
  • 70

2 Answers2

3

You've created two instances of global_var. One is defined in liba.so, and that's the one that b.c is referencing.

The other is defined in a, and that's the one that your main() function is referencing.

If you want your main function to reference the variable in liba.so, it needs an extern declaration of it instead of a definition, and it needs to link against that library itself.

caf
  • 233,326
  • 40
  • 323
  • 462
0

Interesting question. The answer is also interesting.

As caf mentioned in his reply, you have created two definitions of global_var.

To do what you are trying to achieve, you have to make sure that, global_var is resolved from main executable. for that , you will have to create an import file which states that, global_var is imported from main executable. In the import file, you should use #!. for this.

Then use this import file while creating the library.

Also while compiling the main binary, make sure that the global_var variable is exported. use appropriate compiler flags.

On my unix box, i tried this and it works.

# cat imp.imp
 #!.

 global_var

cc main.c -bexpall
cc  lib.c -bM:SRE -bnoentry -bI:./imp.imp -bexpall -o libb.so
user229044
  • 232,980
  • 40
  • 330
  • 338
cexpert
  • 26
  • 2