linux 下共享库创建及使用

1.创建共享库

[xpan@localhost 2.5.3]$ ls

libhello.c libhello.h usehello.c

[xpan@localhost 2.5.3]$ gcc -fPIC -Wall -g -c libhello.c

参数说明:

-fPIC 参数生成与位置无关的代码;

-W 或 -Wall 去除所有警告;

-g 指加上调试信息;

-c 是编译之意;

[xpan@localhost 2.5.3]$ ls libhello.o

libhello.o

[xpan@localhost 2.5.3]$ gcc -shared -o libhello.so.1.0 libhello.o

[xpan@localhost 2.5.3]$ ls

libhello.c libhello.h libhello.o libhello.so.1.0 usehello.c

[xpan@localhost 2.5.3]$ ln -sf libhello.so.1.0 libhello.so

[xpan@localhost 2.5.3]$ ls

libhello.c libhello.h libhello.o libhello.so libhello.so.1.0 usehello.c

[xpan@localhost 2.5.3]$ ls libhello.so -l

lrwxrwxrwx 1 xpan xpan 15 6月 11 09:36 libhello.so -> libhello.so.1.0

[xpan@localhost 2.5.3]$

2.使用共享库

[xpan@localhost 2.5.3]$ ls

libhello.c libhello.h libhello.o libhello.so libhello.so.1.0 usehello.c

[xpan@localhost 2.5.3]$ cat libhello.h

#ifndef _libhello_H_

#define _libhello_H_

void print_hello(void);

#endif /*_libhello_H_*/

[xpan@localhost 2.5.3]$ cat usehello.c

#include "libhello.h"

/*hello*/

int main(void)

{

print_hello();

return 0;

}

[xpan@localhost 2.5.3]$ gcc -Wall -g -c usehello.c -o usehello.o //编译

[xpan@localhost 2.5.3]$ ls

libhello.c libhello.o libhello.so.1.0 usehello.o

libhello.h libhello.so usehello.c

[xpan@localhost 2.5.3]$ gcc -g -o usehello_dynamic usehello.o -L ./ -lhello    //连接引用

[xpan@localhost 2.5.3]$ ls

libhello.c libhello.o libhello.so.1.0 usehello_dynamic

libhello.h libhello.so usehello.c usehello.o

[xpan@localhost 2.5.3]$ ldd usehello_dynamic

linux-gate.so.1 => (0xb7726000)

libhello.so => not found            

libc.so.6 => /lib/libc.so.6 (0x4c645000)

/lib/ld-linux.so.2 (0x4c622000)

[xpan@localhost 2.5.3]$ LD_LIBRARY_PATH=$(pwd) ./usehello_dynamic

hello world ,this is library

指定库的搜索路径

1. LD_LIBRARY_PATH=$(pwd)

2. 拷贝此库"libhello.so"到/usr/lib 或 /lib 文件夹中,或者在此两个文件夹任意一个中创建一个到该库的快捷方式 ,并命名为libname.so;

3. 在"/etc/ld.so.conf"中,每一行添加一个路经,完成以上设置后再运行ldconfig命令更新信息,加入的目录下的所有库文件都可见。当静态库和动态库同名时, gcc命令将优先使用动态库。