如下是一个简单的例子
C文件1 test.c
// test.c
extern void printInAnotherFunc();
int main() {
printInAnotherFunc();
}
C文件2 anotherFunc.c
#include <stdio.h>
void printInAnotherFunc(){
printf("In another Func\n");
}
Makefile
# LD_LIBRARY_PATH 是一个环境变量,用于指定动态链接库(shared library)的搜索路径。
# 当一个程序需要调用动态链接库中的函数时,系统会根据 LD_LIBRARY_PATH 中指定的路径
# 去搜索相应的动态链接库文件。这个环境变量对于程序的运行十分重要,特别是当你安装了
# 一些自定义的动态链接库或者将动态链接库安装在非系统默认的路径下时,你可能需要设置
# 这个环境变量来告诉系统去哪里搜索这些库文件。
run: libanotherFunc.so test.c
gcc test.c -L. -lanotherFunc -o test
LD_LIBRARY_PATH=$(shell pwd) ./test
libanotherFunc.so: anotherFunc.c
gcc -c -fPIC anotherFunc.c -o anotherFunc.o
gcc -shared -o libanotherFunc.so anotherFunc.o
.PHONY: clean
clean:
-@rm -f *.o a.out test *.so
运行 make run,结果如下
user@host a-path-to-cwd> make run
gcc -c -fPIC anotherFunc.c -o anotherFunc.o
gcc -shared -o libanotherFunc.so anotherFunc.o
gcc test.c -L. -lanotherFunc -o test
LD_LIBRARY_PATH=$(shell pwd) ./test
In another Func
这里需要注意的时,在编译阶段,有个命令
gcc test.c -L. -lanotherFunc -o test
这里的 -L. -lanotherFunc 指定了动态链接库的位置和名字,但是这个指定位置和名字仅仅与“链接”阶段有关系,并不会影响到程序的执行阶段。在程序的执行阶段,我们需要再次指定动态链接库的位置,所以才有了后来的 LD_LIBRARY_PATH=$(shell pwd)