1. 程式人生 > >gcc編譯-同時包含靜態庫和共享庫

gcc編譯-同時包含靜態庫和共享庫

1. 當在同一個目錄下靜態庫和共享庫同名時,共享庫優先

hello.h標頭檔案

#ifndef HELLO_H
#define HELLO_H
void print_hello();
#endif

hello.c原始檔
#include "hello.h"
#include <stdio.h>
int main(int argc,char *argv[])
{
	printf("hello world!");
}

測試使用原始檔main.c
#include "hello.h"
int main(int argc,char *argv[])
{
	printf_hello();
}

1.1 編譯靜態庫和共享庫

[[email protected] hello]$ ls
hello.c  hello.h  main.c
[[email protected] hello]$ gcc -c hello.c
[[email protected] hello]$ ar crs libhello.a hello.o
[[email protected] hello]$ gcc -shared -fPIC -o libhello.so hello.o
[[email protected] hello]$ ls
hello.c  hello.h  hello.o  libhello.a  libhello.so  main.c

1.2 使用hello庫編譯 main.c

[[email protected] hello]$ gcc main.c -o main -L. -lhello -I.
[[email protected] hello]$ ldd main
	linux-gate.so.1 =>  (0x00a11000)
	libhello.so => /home/test/programs/c/hello/libhello.so (0x0024b000)
	libc.so.6 => /lib/libc.so.6 (0x0024d000)
	/lib/ld-linux.so.2 (0x0011f000)

看的出, gcc選擇的是libhello.so, 即共享庫優先

2. 當同一目錄下存在同名靜態庫和共享庫, 那麼怎樣選擇靜態庫那?

[[email protected] hello]$ ls
hello.c  hello.h  hello.o  libhello.a  libhello.so  main.c
[[email protected] hello]$ gcc -static main.c -o main -L. -lhello -I. #使用-static 引數阻止連結共享庫
[[email protected] hello]$ ls
hello.c  hello.h  hello.o  libhello.a  libhello.so  main  main.c
[[email protected] hello]$ ldd main
	not a dynamic executable

看的出, gcc此次選擇的是libhello.a, 即靜態庫

3. 編譯程式中同時包含靜態庫和共享庫

*********hello.h程式碼同上******************
*********hello.c程式碼同上******************

calculate.h標頭檔案

//calculate.h
#ifndef CALCULATE_H
#define CALCULATE_H
int add(int a,int b);
#endif

calculate.c原始檔
//calculate.c
#include "calculate.h"

int add(int a,int b)
{
    return a+b;
}

新的測試檔案main.c
#include "hello.h"
#include "calculate.h"
#include <stdio.h>
int main(int argc,char *argv[])
{
    print_hello();
    int res=add(1,2);
    printf("\n1+2=%d\n",res);
}

3.1 將hello的靜態庫檔案libhello.a刪除,保留共享庫檔案libhello.so

3.2 編譯calculate成為靜態庫libcalculate.a

[[email protected] hello]$ gcc -c calculate.c
[[email protected] hello]$ ar crs libcalculate.a calculate.o
[[email protected] hello]$ ls
calculate.c  calculate.h  calculate.o  hello.c  hello.h  libcalculate.a  libhello.so  main.c

3.3 使用libcalculate.a和libhello.so編譯main

[[email protected] hello]$ gcc main.c -o main -L. -lhello -lcalculate -I.
[[email protected] hello]$ ls
calculate.c  calculate.h  calculate.o  hello.c  hello.h  libcalculate.a  libhello.so  main  main.c
[[email protected] hello]$ ldd main
	linux-gate.so.1 =>  (0x00769000)
	libhello.so => /home/test/programs/c/hello/libhello.so (0x00c6d000)
	libc.so.6 => /lib/libc.so.6 (0x0013e000)
	/lib/ld-linux.so.2 (0x0011f000)

看得出, 我們成功了:)