Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to linking with dynamic lib (.so) and static libc.a

I'm trying to link with the static libc.a and a dynamic lib .so unsuccessfully.

I've already tryied the following:

  1. Firstly I test with all dynamic:

    • gcc -shared libtest.c -o libtest.so
    • gcc -c main.c -o main.o
    • gcc main.o -o test -L. -ltest

    It's working (compile and execute)

  2. Secondly I test what I want (dynamic lib and static libc) :

    • gcc -shared libtest.c -o libtest.so
    • gcc -c main.c -o main.o
    • gcc main.o -o test libtest.so /usr/lib/libc.a

    It's compiling, but at execution, it segfault! A strace show that it's trying to access libc.so!!!

  3. Finally I've tried to compile a simple progam with no reference to dynamic lib

    • gcc -static main.c --> compile ok, run ok
    • gcc main.c /usr/lib/libc.a --> compile ok, run : segmentation fault (a strace show that it's access to libc.so)

How to do that?

Thank you

like image 935
Alexxx Avatar asked Feb 01 '10 11:02

Alexxx


Video Answer


1 Answers

Your second test (the one you want to do) is working for me on i686-linux:

$ cat libtest.c 
#include <stdio.h>
void foo() { printf("%d\n", 42); }
$ cat main.c
#include <stdio.h>
extern void foo();
int main() { puts("The answer is:"); foo(); }
$ export LD_LIBRARY_PATH=$PWD                                                                                              
$ gcc -shared libtest.c -o libtest.so && gcc -c main.c -o main.o && gcc main.o -o test -L. -ltest && ./test        
The answer is:
42
$ gcc -shared libtest.c -o libtest.so && gcc -c main.c -o main.o && gcc main.o -o test libtest.so /usr/lib/libc.a && ./test
The answer is:
42

However, you have to realise that the shared library you've build depends on the shared libc. So, it's natural that it's trying to open it at runtime.

$ ldd ./libtest.so 
    linux-gate.so.1 =>  (0xb80c7000)
    libc.so.6 => /lib/i686/cmov/libc.so.6 (0xb7f4f000)
    /lib/ld-linux.so.2 (0xb80c8000)

One way to achieve what you want is to use: -static-libgcc -Wl,-Bstatic -lc.

like image 178
F'x Avatar answered Oct 23 '22 05:10

F'x