制作:
步骤一:
写test.h文件:
void print();
写test.c文件:
#include <stdio.h>
#include "test.h"
void print()
{
printf("I am a little bit hungry now.\n");
}
步骤二:
制作动态链接库, 如下:
[taoge@localhost learn_c]$ ls
test.c test.h
[taoge@localhost learn_c]$ gcc -c test.c
[taoge@localhost learn_c]$ ls
test.c test.h test.o
[taoge@localhost learn_c]$ gcc -shared -fPCI -o libtest.so test.o
[taoge@localhost learn_c]$ ls
libtest.so test.c test.h test.o
[taoge@localhost learn_c]$ file libtest.so
libtest.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (GNU/Linux), dynamically linked, not stripped
[taoge@localhost learn_c]$
使用:
步骤一:
写应用程序main.c, 如下:
#include "test.h"
int main()
{
print();
return 0;
}
步骤二:
libtest.so和test.h, 使用它们, 如下(要注意, 如下编译命令, 并没有把libtest.so编译到a.out中, 理论上也没有。实际上也可以用strings命令验证一下, 确实没有):
[taoge@localhost learn_c]$ ls
libtest.so main.c test.h
[taoge@localhost learn_c]$ gcc main.c -L. -ltest
[taoge@localhost learn_c]$ ./a.out
./a.out: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
[taoge@localhost learn_c]$ cp libtest.so /usr/lib
cp: cannot create regular file `/usr/libtest.so': Permission denied
[taoge@localhost learn_c]$ su root
Password:
[root@localhost learn_c]# cp libtest.so /usr/lib
[root@localhost learn_c]# ./a.out
I am a little bit hungry now.
[root@localhost learn_c]# exit
exit
[taoge@localhost learn_c]$ ./a.out
I am a little bit hungry now.
[taoge@localhost learn_c]$ ls
a.out libtest.so main.c test.h
[taoge@localhost learn_c]$ rm libtest.so test.h main.c
[taoge@localhost learn_c]$ ls
a.out
[taoge@localhost learn_c]$ ./a.out
I am a little bit hungry now.
[taoge@localhost learn_c]$
可见, 要把动态链接库放到/usr/lib下, 才能被加载, 而要在这个目录下添加文件, 必须有root权限。 其余的, 不说自明吧。