本文简单介绍共享库的生成与使用
当前目录下有三个文件,我们稍后会将plus.c编译成为共享库so文件以供main调用
$ls
main.c plus.c plus.h
main.c
#include <stdio.h> #include "plus.h" int main(int argc, char** argv) { int a = 10; int b = 5; printf("a + b = %d\n", plus(a, b)); return 0; }
plus.c
// plus.c int plus(int a, int b) { return a+b; }
plus.h
#ifndef PLUS_H_ #define PLUS_H_ int plus(int a, int b); #endif
第一步:
使用gcc编译,记得加上PIC 选项,这样生成的plus.o才能生成共享库
$ gcc -fPIC -c plus.c
$ ls
main.c plus.c plus.h plus.o
第二步:
同样使用gcc能编译出so文件,加上shared,这样生成的so库才能共享使用
$ gcc -shared plus.o -o libplus.so
$ ls
libplus.so main.c plus.c plus.h plus.o
第三步:
使用gcc生成执行程序main,命令如下。
$ gcc main.c -L. -lplus -o main
$ ls
libplus.so main main.c plus.c plus.h plus.o
$ ./main
a + b = 15
(如果不能运行请设置变量export LD_LIBRARY_PATH=./,使得./main可以在当前路径找到依赖库)
虽然篇没有makefile的知识,但对于我们以后理解makefile会很有帮助。^ ^