首先我们来看一个简单的程序:
//lib_so1.c
int fun();
int fun_so()
{
fun();
return 0;
}
//main.c
#include <stdio.h>
int fun_so();
int fun()
{
printf("in main\n");
return 0;
}
int main()
{
fun_so();
return 0;
}
#Makefile
all:main
lib_so1.so: lib_so1.o
gcc -shared -o $@ $<
main: main.o lib_so1.so
gcc -o $@ main.o -l_so1 -L. -Wl,--rpath=.
%.o : %.c
gcc -fPIC -c $< -o $@
clean:
rm -rf *.o *.a *.so main
程序调用关系很简单,main()->fun_so()->fun(),其中fun_so函数定义在动态库中,其他两个函数定义在main.o中,更多的情况是fun函数通过函数指针的方式传入,但是为了简单,我们是直接使用在动态库调用。
# make
gcc -fPIC -c main.c -o main.o
gcc -fPIC -c lib_so1.c -o lib_so1.o
gcc -shared -o lib_so1.so lib_so1.o
gcc -o main main.o -l_so1 -L. -Wl,--rpath=.
# ./main
in main
运行输出正常。然后我们修改一下程序&#