Lib.h
1 #ifndef LIB_H
2 #define LIB_H
3
4
5 void foobar(int i);
6
7 #endif
_________________________________________________________
Lib.c
1 #include
2
3 void foobar(int i)
4 {
5 printf("Printing From Lib.so %d\n",i) ;
6 sleep(-1);
7
8 }
__________________________________________________________
program_1.c
1 #include "Lib.h"
2
3 int main()
4 {
5 foobar(1);
6 return 0;
7 }
__________________________________________________________
root@libin:~/project/dso# ll
总用量 20
drwxr-xr-x 2 root root 4096 2010-10-21 22:58 ./
drwxr-xr-x 8 libin libin 4096 2010-10-21 22:17 ../
-rw-r--r-- 1 root root 99 2010-10-21 22:42 Lib.c
-rw-r--r-- 1 root root 59 2010-10-21 22:18 Lib.h
-rw-r--r-- 1 root root 58 2010-10-21 22:30 program_1.c
生成共享对象文件的命令
root@libin:~/project/dso# gcc -fPIC -shared -o Lib.so Lib.c
-shared 表示生成共享对象
-fPIC 暂不解释
root@libin:~/project/dso# ll
总用量 28
drwxr-xr-x 2 root root 4096 2010-10-21 22:59 ./
drwxr-xr-x 8 libin libin 4096 2010-10-21 22:17 ../
-rw-r--r-- 1 root root 99 2010-10-21 22:42 Lib.c
-rw-r--r-- 1 root root 59 2010-10-21 22:18 Lib.h
-rwxr-xr-x 1 root root 6772 2010-10-21 22:59 Lib.so*
-rw-r--r-- 1 root root 58 2010-10-21 22:30 program_1.c
这样在当前目录下就生成了共享对象文件Lib.so。这个共享对象文件包含foobar函数。
然后我们就可以编译链接我们的program_1.c
root@libin:~/project/dso# gcc -o program program_1.c ./Lib.so
root@libin:~/project/dso# ll
总用量 36
drwxr-xr-x 2 root root 4096 2010-10-21 23:00 ./
drwxr-xr-x 8 libin libin 4096 2010-10-21 22:17 ../
-rw-r--r-- 1 root root 99 2010-10-21 22:42 Lib.c
-rw-r--r-- 1 root root 59 2010-10-21 22:18 Lib.h
-rwxr-xr-x 1 root root 6772 2010-10-21 22:59 Lib.so*
-rwxr-xr-x 1 root root 7134 2010-10-21 23:00 program*
-rw-r--r-- 1 root root 58 2010-10-21 22:30 program_1.c
阅读(3139) | 评论(1) | 转发(1) |