Naveen Kumar Naveen Kumar - 1 month ago 7
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 common_add.so

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 common_add.so 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 common_add.so
*/
extern int_32 g_test_variable; //declaration
int add_int(int a, int b)
{
if(g_test_variable)
printf("somthing");

return a+b;
}

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

Answer

(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 common_add.so

But if aa does not define the symbol g_test_variable (in some global ELF symbol table) its dynamic linking of common_add.so 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 common_add.so 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).