本篇文章我们来编写CMakeLists.txt使用cmake的add_library的构建静态库,并使用target_link_libraries链接指定的静态库。
cmake的linux windows 和linux环境的准备可以我看前面的文章:
一 代码准备
为了项目更简单点,我这边把静态库和配置和链接静态库的配置放在一个CMakeLists.txt文件中
下面是文件列表(所有文件在同一个目录)
xlog.h
xlog.cpp
test_xlog.cpp
CMakeLists.txt
下面我们分别来看下每个文件中的内容,首先是库的代码xlog.h 和xlog.cpp 。
- //xlog.h
- #ifndef XLOG_H
- #define XLOG_H
- #include
- class XLog
- {
- public:
- void Add(std::string log);
- };
- #endif
- // xlog.cpp
- #include "xlog.h"
- #include
- using namespace std;
- void XLog:
- :Add(std::string log)
- {
- cout<
- }
二 CMake 编译静态库 add_library
下面我们来编写CMakeLists.txt
- cmake_minimum_required (VERSION 3.0)
- project (xlog)
- add_library(xlog STATIC xlog.cpp)
其中头文件可以加入到 add_library中,比如 add_library(xlog STATIC xlog.cpp xlog.h) 这样保证依赖关系,头文件更改时库也会重新编译。
add_library中的第二个参数 STATIC 表示是静态库,如果不加STATIC的话比如 add_library(xlog xlog.cpp) 就是默认编译动态库,如果要编译静态库再通过cmake的预制变量来控制。
STATIC 替换为SHARED 就是指定编译为动态库,例如:add_library(xlog SHARED xlog.cpp) 。
如果是Linux动态库代码不需要调整,Windows动态库需要在代码中添加 __declspec(dllexport)不然导不出lib文件。
下面在CMakeLists.txt所在目录运行
cmake -S . -B build
cmake --build build
三 CMake 链接静态库
静态库就编译完成,下面引入静态库,添加测试的程序test_xlog.cpp并且再次编辑CMakeLists.txt
//test_xlog.cpp
- //test_xlog.cpp
- #include
- #include "xlog.h"
- using namespace std;
- int main(int argc,char *argv[])
- {
- out<<"test cmake lib"<
- XLog log;
- log.Add("test xlog");
- return 0;
- }
#CMakeLists.txt
- #CMakeLists.txt
- cmake_minimum_required (VERSION 3.0)
- project (xlog)
- add_library(xlog STATIC xlog.cpp)
- add_executable(test_xlog test_xlog.cpp)
- # 指定加载的库
- target_link_libraries(test_xlog xlog)
再次运行
cmake -S . -B build
cmake --build build
就编译出静态库和导入静态库的测试程序。


更多的资料可以看cmake官方手册 cmake.org.cn
-
相关阅读:
bootstrap按钮
公链常用的共识算法
Simulink的serial系列无法识别硬件串口的解决方法
如何使用html、css制作一个期末作业网站【羽毛球体育运动主题html网页设计】
基于Springboot Aop实现注解鉴权式框架
图聚类算法(Graph clustering)
package.json
sql跨表查询的三种方案
uni-app进阶之生命周期【day8】
CentOS中yum install命令如何找到安装包的下载地址
-
原文地址:https://blog.csdn.net/jiedichina/article/details/126687785