468,513 Members | 941 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,513 developers. It's quick & easy.

Global variables in Shared Libraries in Linux

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

Sep 4 '06 #1
1 5007
ni******@gmail.com wrote:
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

Sep 4 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

10 posts views Thread by Matt | last post: by
4 posts views Thread by Dan Elliott | last post: by
reply views Thread by nidumolu | last post: by
5 posts views Thread by Sandman | last post: by
15 posts views Thread by =?Utf-8?B?UGF0Qg==?= | last post: by
3 posts views Thread by ankugoe7 | last post: by
4 posts views Thread by stuntgoat | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.