1. g++进行编译并调用.so库

目录/home/test_ws/src/

文件1:

test1.h

#include <iostream>
using namespace std;
void test();

文件2:

test1.cpp

#include "test1.h"
void test()
{
    std::cout << "this is a test log" << std::endl;
}

文件3:

main.cpp

#include "test1.h"
int main()
{
    test();
}
g++ -std=c++11 test1.cpp -shared -fPIC -o test1.so  #在src下生成test1.so的动态库文件

g++ main.cpp test1.so -o main  #在src下生成main的可执行文件

./main会报错

./main: error while loading shared libraries: test1.so: cannot open shared object file: No such file or directory

这是因为链接器ld默认的目录是/lib和/usr/lib,如果放在其他路径也可以,需要让ld知道库文件在哪里。 

使用如下命令

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/test_ws/src/

将存放test1.so的文件夹导入到ld连接器中即可,但是计算机重启将会失效,需要重新导入。

运行

./main

结果

this is a test log

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐