linux环境指定动态链接库路径
创建一个动态链接库
gcc -shared -fpic -o libqazwsx.so
这条命令将x1.o x2.0 x3.o三个文件打包成一个动态链接库文件libqazwsx.so
链接这个动态链接库,并放在可执行文件目录下,使可执行文件执行时能找到这个库
你可以使用 ldd 看看它所链接的动态库
gcc test.o -o test -Wl,-rpath,./ -L./ -lqazwsx
这个是文件目录
.--test
|
|-------test.c
|-------x1.c
|-------x2.c
|-------x3.c
|
|-------test.o
|-------x1.o
|-------x2.o
|-------x3.o
|
|-------libqazwsx.so
解释一下命令
test.o -o test将test.o与动态库链接并输出可执行文件test
-Wl,-rpath,./告诉链接器,test执行时在./下找动态库
-L./ -lqazwsx 告诉链接器,链接时在./下找库
给出代码
x1.c
#include
void print_x1 (void) {
printf("I am x1.o\n");
}
x2.c
#include
void print_x2 (void) {
printf("I am x2.o\n");
}
x3.c
#include
void print_x3 (void) {
printf("I am x3.o\n");
}
test.c
#include
extern void print_x1 (void);
extern void print_x2 (void);
extern void print_x3 (void);
int main (void) {
print_x1();
print_x2();
print_x3();
printf("I am main function\n");
return 0;
}
完整的编译指令
gcc -c x1.c
gcc -c x2.c
gcc -c x3.c
gcc -c test.c
gcc -shared -fpic x1.o x2.o x3.o -o libqazwsx.so
gcc test.o -o test -Wl,-rpath,./ -L./ -lqazwsx
下面看一下测试(截图上传我不太会玩,复制粘贴好了)
# ??? @ ??? in ~/workspace/cpp [19:18:35]
$ ./test
I am x1.o
I am x2.o
I am x3.o
I am main function
# ??? @ ??? in ~/workspace/cpp [19:18:39]
$ ldd test
linux-vdso.so.1 (0x00007fff755fd000)
libqazwsx.so => ./libqazwsx.so (0x00007f9708264000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9707ea2000)
/lib64/ld-linux-x86-64.so.2 (0x0000564acd3d3000)
# ??? @ ??? in ~/workspace/cpp [19:22:57]
$ rm libqazwsx.so
rm:是否删除普通文件 'libqazwsx.so'?y
# ??? @ ??? in ~/workspace/cpp [19:23:04]
$ ./test
./test: error while loading shared libraries: libqazwsx.so: cannot open shared object file: No such file or directory
# ??? @ ??? in ~/workspace/cpp [19:23:07] C:127
$ ldd test
linux-vdso.so.1 (0x00007ffda6fdb000)
libqazwsx.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f702f741000)
/lib64/ld-linux-x86-64.so.2 (0x000055c80d664000)