Global variables in Shared Libraries in Linux

N

nidumolu

Hi,

Can I have a Global variable declared in the application, be used in a
shared library opened through 'dlopen' ? For example:

I have a Library 'libfoo.so' with the following:

libfoo_headerfile.h
=============

extern int my_global_var;


libfoo_foo.c
========
#include "libfoo_headerfile.h"

int
foo (void)
{
my_global_var = 512;
printf("shared_lib %s - my_global_var = %d\n", __FUNCTION__,
my_global_var);
return 10;
}



I have the following in my Application:
============================

app.c
====

#include "libfoo_headerfile.h"

int my_global_var;

int
main ()
{
char *error;
void *handle;
int (*foo_fn_p) (void);

handle = dlopen("libfoo.so", RTLD_LAZY);
if (!handle) {
fputs (dlerror(), stderr);
exit(1);
}
printf("Main - After dlopen - my_global_var = %d\n",
my_global_var);

foo_fn_p = dlsym(handle, "foo");
if ((error = dlerror()) != NULL) {
printf("Error in dlsym");
fputs(error, stderr);
exit(1);
}

printf("foo_fn_p = %u\n", foo_fn_p());
dlclose(handle);
handle = NULL;
printf("Main - after dlclose - shared_lib_var = %d\n",
shared_lib_var);

return 1;
}

Here is my Make File:

all:
gcc -fPIC -g -c libfoo_foo.c
gcc -shared -o libfoo.so libfoo_foo.c
gcc -g -o app app.c -ldl

clean:
rm -f *.o
rm -f *.so
rm -f app

When executing 'app' I am seeing the following error:

/users/nkalyan/test/shared_libraries/libfoo.so: undefined symbol:
my_global_var

Looks like the Shared library is not recognizing 'my_global_var'.
Any ideas
 
R

Robert Gamble

Hi,

Can I have a Global variable declared in the application, be used in a
shared library opened through 'dlopen' ?

dlopen is not a Standard C function and thus off-topic here. Try
comp.unix.programmer.

Robert Gamble
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top