This is the mail archive of the
libc-help@sourceware.org
mailing list for the glibc project.
Re: Global variables and shared libraries
On Wed, Nov 28, 2012 at 11:53:18AM +0530, Siddhesh Poyarekar wrote:
> On 28 November 2012 11:11, Bharath Ramesh <bramesh@vt.edu> wrote:
> > I want to export a global variable that has been defined in a
> > shared library to the binary that links with it. The most common
> > approach would be to declare the global variable as an extern
> > variable in the application code. This approach would make the
> > actual reference to the global variable be present in the data
> > segment of the binary. My use case would require that the
>
> No it wouldn't, unless the binary is statically linked. It comes up
> as an undefined symbol in the binary and it is resolved at runtime by
> the dynamic linker. You can see this by doing an `objdump -x` on the
> generated binary. The global variable is defined in the data section
> of the DSO binary.
I am then definitely doing something wrong. I am attaching two
simple test files and compile them as follows.
libfoo:
gcc -g -Wall -Wextra -O3 -fPIC -c foo.c
gcc -g -Wall -Wextra -O3 -shared -Wl,-soname,libfoo.so -o libfoo.so foo.o
test:
gcc -g -Wall -Wextra -O3 -o test test.c -Wl,-rpath . -L . -lfoo
Now, if I run "nm" on test I get the following
$ nm ./test | grep foo
0000000000601028 B foo
Which indicates foo is in the data segment of the binary. The
output of the test reflects the same.
$ ./test
foo: 1
address of foo: 0x601028
Would appreciate it if I know what I am doing wrong.
> > segment after linking. I was thinking some what in the way errno
> > is linked, but I believe it ends up as a function call eventually
> > so that appropriate address can be dereferenced, please do
> > correct me if I am wrong. I do not want to access the variable
>
> errno is a thread-local variable and __errno_location returns the
> value from the TLS variable, which is defined in the .tbss section in
> libc.so.
Thank you for the clarification.
>
> > using get/set calls either. If this is not the appropriate forum
> > for this question, I would greatly appreciate it if you could
> > point me in the direction of a more suitable forum as well.
>
> This is the right forum for this question.
--
Bharath
#include <stdio.h>
int foo = 1;
void bar(void)
{
printf("address of foo: %p\n", &foo);
return;
}
#include <stdio.h>
#include <stdlib.h>
extern void bar(void);
extern int foo;
int main(int argc, char *argv[])
{
printf("foo: %d\n", foo);
bar();
return EXIT_SUCCESS;
}