cmake add_library编译链接静态库cmakelists

   本篇文章我们来编写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 <string>
class XLog
{
public: void Add(std::string log);
};
#endif
// xlog.cpp 
#include "xlog.h" #include <iostream> using namespace std; void XLog::Add(std::string log) { cout<<log<<endl; }

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 <iostream>
#include "xlog.h" 
using namespace std; 
int main(int argc,char *argv[])
{
out<<"test cmake lib"<<endl; 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

如果想要学习CMake更多内容,可以看下我的这门课程:

 

posted @ 2022-09-04 12:46  老夏课堂-夏曹俊  阅读(899)  评论(0编辑  收藏  举报