Problem with static linking
Hendrik Muhs
Hendrik.Muhs@student.uni-magdeburg.de
Fri Jan 18 10:44:00 GMT 2002
Hi,
I have a problem with static linking. Please look at the following example.
The main programm foo "dlopens" the shared library bar and calls the function
in bar.
If I compile at least bar.c or foo.c not static:
gcc -o foo foo.c -ldl
gcc -shared -o bar.so bar.c
or
gcc -static -o foo foo.c -ldl
gcc -shared -o bar.so bar.c
or
gcc -o foo foo.c -ldl
gcc -shared -o bar.so bar.c -Wl,-static
it works. But if compile both static:
gcc -static -o foo foo.c -ldl
gcc -shared -o bar.so bar.c -Wl,-static
I get a segfault(in malloc):
hendrik@tux:~> ./foo
we are in bar
Segmentation fault
I tried it with different versions of gcc: 2.95.3, 3.0.3(both SuSE Linux 7.3)
and 2.96(Redhat Linux 7.2)
the code:
//foo.c
#include <stdio.h>
#include <dlfcn.h>
int main (void)
{
void *lib;
int (*sym)(void);
lib = dlopen("./bar.so", RTLD_NOW);
if (!lib) {
fputs (dlerror(), stderr);
exit(1);
}
sym = dlsym(lib, "bar");
(*sym)();
dlclose(lib);
return 0;
}
//bar.c
#include <stdlib.h>
#include <malloc.h>
int bar(void)
{
char *buf;
printf("we are in bar\n");
buf = malloc(5);
printf("return to foo\n");
return 0;
}
Why does it segfaults?
Thanks in advance,
Hendrik
More information about the Gcc-help
mailing list