Linux库多重依赖

源文件:

//world.cpp
#include <stdio.h>

void world(void)
{
    printf("world.\n");
}
//hello.cpp
#include <stdio.h>

void world(void);

void hello(void)
{
    printf("hello\n");
    world();
}
//test.cpp

void hello(void);

int main(void)
{
    hello();
    return 0;
}

 一、动态库多重依赖

(1)编译word动态库

g++ -shared -fPIC world.cpp -o libworld.so

(2)编译hello动态库

g++ -shared -fPIC hello.cpp -o libhello.so

ldd libhello.so

查看libhello.so的依赖库,没有看到依赖libword.so

g++ -shared -fPIC hello.cpp -o libhello.so -L ./ -lworld

ldd libhello.so

再次查看libhello.so的依赖库,看到了依赖库libword.so

上图显示libworld.so not found,如果临时增加链接动态库的路径,输入如下命令

export LD_LIBRARY_PATH=./

ldd libhello.so

查看libhello.so的依赖库,显示了依赖库libword.so的路径

先清除链接动态库路径

export LD_LIBRARY_PATH=

(3)编译可执行文件test

g++ test.cpp -o a.out -L ./ -lhello

提示找不到libhello.so的依赖库libworld.so,即使编译libhello.so时已经指定了libworld.so,这点和windows不一样

g++ test.cpp -o a.out -L ./ -lhello -lworld -Wl,-rpath ./

编译通过,得到可执行文件a.out,运行成功

二、动态库静态库多重依赖

(1)编译word静态库

g++ -c world.cpp

ar -cr libworld.a world.o

(2)编译hello动态库

g++ -shared -fPIC hello.cpp -o libhello.so -L ./ -lworld

编译报错,因为world也必须使用-fPIC,重新编译

(3)编译可执行文件

g++ test.cpp -o a.out -L ./ -lhello -Wl,-rpath ./

三、静态库多重依赖

(1)编译world静态库

g++ -c world.cpp

ar -cr libworld.a world.o

(2)编译hello静态库

g++ -c hello.cpp

ar -cr libhello.a hello.o

(3)编译可执行文件

g++ test.cpp -o a.out -L ./ -lworld -lhello

因为静态库的依赖有顺序,被调用库应该放在调用库后面,动态库没有依赖顺序,正确输入如下

g++ test.cpp -o a.out -L ./ -lhello -lworld

 (4)静态库包含静态库

 

posted @ 2018-06-07 11:27  pinhole  阅读(1984)  评论(0编辑  收藏  举报