Linux下构建自己的C++共享库并配合pkg-config生成链接选项
本文将以C++链表的新建、打印操作为例构建自己的共享库,并在实际调试代码时尝试使用。我们在做数据结构题时经常需要将链表打印出来看一下结果,但是并没有一种库函数可以让我们直接调用来打印自己的基于ListNode的链表(LeetCode的题目通常是这样的链表)。因此本文将以此为例,介绍怎样构建自己的动态链接库,并通过pkg-config生成对应的链接选项。
编译生成共享库并添加到环境变量
源文件编译生成共享库
我们的链表库的源代码LinkedList.cpp
是这样的,仅有两个函数新建、打印做例子。其源文件和头文件如下:
// LinkedList.cpp
#include <iostream>
#include <vector>using namespace std;struct ListNode{int val;ListNode* next;ListNode(int x) : val(x), next(NULL) {}
};ListNode* createList(const vector<int> vec){ListNode* head = new ListNode(0);ListNode* prev = head;for (int i : vec){ListNode* next = new ListNode(i);head->next = next;head = next;}return prev->next;
}void printList(ListNode* head){ListNode* p = head;while(p){cout << p->val << " -> ";p = p->next;}cout << "nullptr" << endl;
}// dsutils.h
#include <iostream>
#include <vector>
using namespace std;struct ListNode;
ListNode* createList(const vector<int> vec);
void printList(ListNode* head);
我们先来编译链接生成共享库:
g++ -shared -fpic LinkedList.cpp -o libmlist.so
由于我们的共享库要在运行时动态链接,因此需要将它放到特定的目录下,并将该目录添加到环境变量LD_LIBRARY_PATH
,否则会在运行时报找不到库的错误。(关于动态链接与加载,可参考:Linux下的ELF文件、链接、加载与库(含大量图文解析及例程))
mkdir /home/song/mlib
cp libmlist.so /home/song/mlib
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/song/mlib
头文件dsutils.h
也放在一个目录下:
mkdir /home/song/minclude
cp dsutils /home/song/minclude
测试代码编译运行
现在我们创建一个测试代码test.cpp
,
// test.cpp
#include <iostream>
#include <vector>#include "dsutils.h"using namespace std;int main(int argc, char* argv[]){vector<int> vec = {1, 2, 3, 4, 5};ListNode* head = createList(vec);printList(head);return 0;
}
其实我们现在就可以用了,只是需要比较复杂的链接选项。我们要这样编译(其选项具体含义可参考:gcc参数 -i, -L, -l, -include):
g++ test.cpp -I/home/song/minclude -L/home/song/mlib -lmlist -o test
就可以正常生成可执行文件了,其运行输出为:
$ ./test
1 -> 2 -> 3 -> 4 -> 5 -> nullptr
但问题时,总不能每次都打这么一长串编译选项,现在只有一个库文件还好,如果大项目中库文件项目多了,就记不住了。这时我们就需要pkg-config工具来帮助我们生成链接选项。
利用pkg-config生成编译链接选项
安装
如果还没有安装过pkg-config工具的读者可以:
下载、解压、安装、验证一气呵成:
# 下载
wget https://pkg-config.freedesktop.org/releases/pkg-config-0.29.2.tar.gz
# 解压
tar -zxvf pkg-config-0.29.2.tar.gz
# 安装
cd pkg-config-0.29.2/
./configure
make
make check
sudo make install
# 验证
pkg-config --version
# 输出:0.29.2 安装成功
配置dsutils.pc
安装完成后,我们需要配置pc文件,来告诉pkg-config如何帮我们生成链接选项,即我们有dsutils.pc
:
lib_dir=/home/song/mlib
include_dir=/home/song/mincludeName: dsutils
Description: My utils of data structure.
Version: 0.1
Cflags: -I${include_dir}
Libs: -L${lib_dir} -lmlist
将配置好的dsutils.pc
放到pkg-config的目录/usr/local/lib/pkgconfig/
下:
这时,可以在命令行中测试一下:
pkg-config dsutils --libs --cflags
一切正常的话会输出:
-I/home/song/minclude -L/home/song/mlib -lmlist
读者可能已经发现了,这就是上面那一串长长的编译链接选项。这样做的另一个好处是,如果我们有更多的dsutils,如libmbtree.so
,可以直接在dsutils.pc
中添加,来增加链接选项,而不用去记那么多的库。
测试
测试只要将上面的选项在编译时添加上即可:
g++ test.cpp -o test `pkg-config dsutils --libs --cflags`
如果一切正常则会产生一个可执行文件test
,运行它,我们将得到输出:
1 -> 2 -> 3 -> 4 -> 5 -> nullptr
如果过程中有报错,请先参考Linux下编译、链接、加载运行C++ OpenCV的两种方式及常见问题的解决。如问题还不能解决,欢迎留言讨论。