Naveen Kumar Naveen Kumar - 1 year ago 71
C Question

What will happen if my process not defined a variable but it is used as a extern variable in a shared library?

I have 2 process A and B. Both process shared same shared object file called

I defined the variable g_test_variable in process A.

But if i not define the variable g_test_variable in process B and open the file using dlopen & dlsym and invoke the add_double function which is not using g_test_variable variable ,will i hit any issue ?

* File Name : common.c
* This file packaged as part of
extern int_32 g_test_variable; //declaration
int add_int(int a, int b)

return a+b;

double add_double(double a, double b)
return a-b;

Answer Source

(I am speaking for Linux systems)

So you have a program aa (running in process A) and a program bb (running in process B). Both are using the

But if aa does not define the symbol g_test_variable (in some global ELF symbol table) its dynamic linking of would fail.

How and when that happens may depend how is the dynamic linking done.

If you are using dlopen(3) you'll better pass RTLD_NOW to avoid lazy linking. Then dlopen would fail and dlerror is giving a useful message.

If you pass the default RTLD_LAZY to dlopen it could happen that the error would trigger only on the first call to add_int or even to the apparently unrelated add_double (but details may vary with implementations)

(don't forget to compiler the common.c with -fPIC for the plugin, and link both main aa & bb programs with -rdynamic)

See also this and read Drepper's How To Write Shared Libraries paper.

I recommend using RTLD_NOW to catch at early dlopen time such errors. Of course, you cannot expect the program to work if an undefined symbol is referenced! (So you should require the main program to define g_test_variable ...). You could consider declaring your g_test_variable as a weak symbol in the plugin (but I generally do not recommend such tricks).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download