gcc 編譯兩個so其中soA依賴soB

有兩個so,其中soB中調用soA;測試

那麼咱們打包soB的時候鏈接soA;blog

在打包test程序的時候鏈接soB,此時soB會自動查找依賴的soA;io

以下測試編譯

在編譯以前指定環境變量:export LD_LIBRARY_PATH=./class

soAtest

#include <stdio.h>

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

 編譯成so變量

	gcc -shared -fPIC -o libadd.so add.c

  

soBgcc

#include <stdio.h>

extern int add(int a,int b);

int cal(int a,int b){

	return (add(a,b)+1);

}

  編譯成so,編譯時鏈接soA,就是 -ladd打包

	gcc -shared -fPIC -o libcal.so cal.c -L. -ladd

  

測試程序test.cfile

#include <stdio.h>


extern int cal(int a,int b);

int main(void)
{
	printf("%d\n",cal(11,10));
	return 0;
}

  編譯測試程序,這裏咱們只是鏈接了cal,沒鏈接add

	gcc test.c  -o test -L. -lcal

 

最後運行test

 

因爲咱們前面指定的環境變量,能夠這麼作,若是不指定環境變量,默認會從系統的庫路徑下查找,那麼找不到so,就沒法編譯咱們的測試程序;

完整的Makefile

all:

	gcc -shared -fPIC -o libadd.so add.c
	gcc -shared -fPIC -o libcal.so cal.c -L. -ladd
	gcc test.c  -o test -L. -lcal


clean:
	rm -rf test
	rm -rf *.so  

 

使用以前要提早設置環境變量;

相關文章
相關標籤/搜索