目录
- [1 概述](#1 概述)
- [2 文件命名](#2 文件命名)
- [3 实例](#3 实例)
- [4 代码分析](#4 代码分析)
1 概述
编译工具有很多(make/cmake/BJam)。cmake是跨平台,使用cmake编译需要编写CMakeLists.txt。本文编写CMakeLists.txt来生成C++静态库。
2 文件命名
文件命名为CMakeLists.txt,是一个文本文件,可以使用任何编辑器编辑。
本文使用cmake程序版本:
bash
$cmake --version
cmake version 3.16.3
CMake suite maintained and supported by Kitware (kitware.com/cmake)
3 实例
这里以CppCmd库代码为例,代码目录结构:
bash
cppcmd$ tree
.
├── CMakeLists.txt
├── cmdhelper.h
├── cmdio.cpp
├── cmdio.h
├── cppcmd.cpp
└── inc
└── cppcmd.h
1 directory, 6 files
CMakeLists.txt文件如下:
c
cmake_minimum_required(VERSION 3.13)
set(CPPCMD_VERSION 1.0.0)
project(cppcmd VERSION ${CPPCMD_VERSION} LANGUAGES CXX)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
include_directories(./inc)
file(GLOB SRC *.cpp)
set(CMAKE_CXX_FLAGS "-std=c++11")
add_library(${PROJECT_NAME} ${SRC})
编译结果:
shell
cppcmd$ mkdir build
cppcmd$ cd build/
build$ cmake ..
-- The CXX compiler identification is GNU 10.5.0
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/james/git/cppcmdv1.0.0/cppcmd/build
james@DESKTOP-GNG18AT:build$ make
Scanning dependencies of target cppcmd
[ 33%] Building CXX object CMakeFiles/cppcmd.dir/cmdio.cpp.o
[ 66%] Building CXX object CMakeFiles/cppcmd.dir/cppcmd.cpp.o
[100%] Linking CXX static library lib/libcppcmd.a
[100%] Built target cppcmd
说明:
- 编译生成静态库libcpptes.a文件放在build/lib目录下
- 编译生成.o放在build/CMakeFiles/cppcmd.dir/目录下
4 代码分析
c
cmake_minimum_required(VERSION 3.13) # 设置使用cmake的最小版本,这里最小版本是3.12
set(CPPCMD_VERSION 1.0.0) # 设置变量CPPCMD_VERSION,其值为1.0.0
project(cppcmd VERSION ${CPPCMD_VERSION} LANGUAGES CXX) # 设置工程名称,版本,开发语言
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) # 设置库文件输出路径为build/lib
include_directories(./inc) # 设置include路径,这里是当前路径下inc目录
file(GLOB SRC *.cpp) # 行设置要编译的源文件,这里将当前路径下所有cpp文件名称,放在变量SRC中
set(CMAKE_CXX_FLAGS "-std=c++11") # 设置定义C++编译选项,C++使用C++11标准
add_library(${PROJECT_NAME} ${SRC}) # 设置静态库名称及依赖的源文件