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.
You’ve created two instances of
global_var. One is defined inliba.so, and that’s the one thatb.cis referencing.The other is defined in
a, and that’s the one that yourmain()function is referencing.If you want your main function to reference the variable in
liba.so, it needs anexterndeclaration of it instead of a definition, and it needs to link against that library itself.