linux創建動態庫

靜態庫的創建和使用:

- g++ add.cpp生成add.o目標文件
- ar cqs libadd.a add.o
	- ar打包目標文件(elf中的relocatable文件)
	- 靜態庫的名字lib[static_library_name].a

- 鏈接靜態庫.
- g++ main.c -L . -ladd
- 靜態庫的鏈接語法和動態庫基本語法一致.

動態庫的創建和使用:

- g++ -fPIC -shaerd add.cpp -o libadd.so
	- shared library的名字格式:lib[name].so
- 動態庫的使用.
- g++ main.c -L . -ladd
- 記得增加鏈接搜索路徑。

	- error常見解析:
		- cannot find -ladd
			- 出現這種錯誤是因爲在編譯鏈接動態庫的時候找不到該動態庫,即沒有指定編譯時的搜索路勁
			- 解決方案見<動態庫的鏈接>
				[root@VM_0_9_centos dynamic_lib_text]# ls
				add.c  add.h  add.o  libadd.so  main.c
				[root@VM_0_9_centos dynamic_lib_text]# g++ main.c 
				/tmp/ccBAOjnr.o: In function `main':
				main.c:(.text+0x13): undefined reference to `add(int, int)'
				collect2: error: ld returned 1 exit status
				[root@VM_0_9_centos dynamic_lib_text]# 

		- undefined reference to `add(int, int)'
			- 編譯時通過 -l指定了動態庫,但是沒有搜索路徑。
				[root@VM_0_9_centos dynamic_lib_text]# ls
				add.c  add.h  add.o  libadd.so  main.c
				[root@VM_0_9_centos dynamic_lib_text]# g++ main.c -ladd
				/usr/bin/ld: cannot find -ladd
				collect2: error: ld returned 1 exit status
				[root@VM_0_9_centos dynamic_lib_text]# 
		- error while loading shared libraries: libadd.so: cannot open shared object file: No such file or directory
			- 運行時找不到鏈接動態庫的路徑。
				[root@VM_0_9_centos dynamic_lib_text]# ls
				add.c  add.h  add.o  libadd.so  main.c
				[root@VM_0_9_centos dynamic_lib_text]# g++ main.c -ladd -L .
				[root@VM_0_9_centos dynamic_lib_text]# ./a.out 
				./a.out: error while loading shared libraries: libadd.so: cannot open shared object file: No such file or directory
				[root@VM_0_9_centos dynamic_lib_text]# 


	- 簡單解決方案:
	- g++ main.c -L . -ladd
	- export LD_LIBRARY_PATH=.
		[root@VM_0_9_centos dynamic_lib_text]# ls
		add.c  add.h  add.o  a.out  libadd.so  main.c
		[root@VM_0_9_centos dynamic_lib_text]# g++ main.c -ladd -L .
		[root@VM_0_9_centos dynamic_lib_text]# ./a.out 
		./a.out: error while loading shared libraries: libadd.so: cannot open shared object file: No such file or directory
		[root@VM_0_9_centos dynamic_lib_text]# export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
		[root@VM_0_9_centos dynamic_lib_text]# ./a.out 
		use dynamic library. iret=39
		[root@VM_0_9_centos dynamic_lib_text]# 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章