从头开始构建一个带第三方库的cmake
程序目录文件
1
2
3
4
5
6
7
8
9root@aw:~/test# tree .
.
├── libsupp # 第三方库文件和头文件
│ ├── include
│ │ └── jansson.h
│ └── lib
│ └── libjansson.a
└── src
└── main.c # 自己项目的源文件首先确定cmake最低版本
1
cmake_minimum_required(VERSION 2.8)
确定项目名
1
project(hello)
设置语言标准
1
set(CMAKE_C_STANDARD 99)
设置编译选项
1
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -g -D_GNU_SOURCE")
指定源文件目录
1
2# ${CMAKE_CURRENT_LIST_DIR}表示CMakeLists.txt文件所在目录
aux_source_directories(${CMAKE_CURRENT_LIST_DIR}/src SOURCE_FILES)指定头文件目录
1
include_directories(${CMAKE_CURRENT_LIST_DIR}/libsupp/include)
指定第三方库文件目录
1
link_directories(${CMAKE_CURRENT_LIST_DIR}/libsupp/lib)
指定目标文件
1
add_executable(${PROJECT_NAME} ${SOURCE_FILES})
需要引用第三方库
1
target_link_libraries(${PROJECT_NAME} jansson)
有时候cmake会报不认识链接库语言的错,加上这个
1
set_target_properties(${PROJECT_NAME} PROPERTIES LINKER_LANGUAGE C)
合起来就是下边这个CMakeLists.txt
1 | cmake_minimum_required(VERSION 2.8) |
- 出现这个错
1
2
3
4
5
6
7
8
9
10
11
12-- The CXX compiler identification is unknown
CMake Error at CMakeLists.txt:2 (PROJECT):
No CMAKE_CXX_COMPILER could be found.
Tell CMake where to find the compiler by setting either the environment
variable "CXX" or the CMake cache entry CMAKE_CXX_COMPILER to the full path
to the compiler, or to the compiler name if it is in the PATH.
-- Configuring incomplete, errors occurred!
See also "/ioda/ipwave_rt/bgpstream/build/CMakeFiles/CMakeOutput.log".
See also "/ioda/ipwave_rt/bgpstream/build/CMakeFiles/CMakeError.log".
但是我的项目是纯C的,用不到CXX,可以设置项目语言为C
1 | PROJECT(hello LANGUAGES C) |
CheckCxxCompilerFlag 模块
检查cxx编译器是否支持某个flag
1 | include(CheckCxxCompilerFlag) |
示例
1 | cmake_minimum_required(VERSION 3.0) |
引入第三方库
1 | add_custom_target(third) |
memo
cmake_minimum_required(VERSION 2.8)
project(sokk)
指定编译器标准 –std=c++11
set(CMAKE_CXX_FLAGS “${CMAKE_CXX_FLAGS} -std=c++11”)指定编译选项
set(CMAKE_CXX_FLAGS “${CMAKE_CXX_FLAGS} -g -Wall”)打开详细输出
set(CMAKE_VERBOSE_MAKEFILE ON)生成DEBUG
set(CMAKE_BUILD_TYPE DEBUG)控制宏定义
add_definitions(-DSPDLOG_HEADER_ONLY=1)
set(SRC src/sokk.cpp)
set(DEPS_STATIC deps/libhv/lib/libhv_static.a)
链接静态库,需要指明具体地址
add_executable(sokk ${SRC} ${DEPS_STATIC})链接动态库
target_include_directories(sokk
PUBLIC ${CMAKE_SOURCE_DIR}/deps/libhv/include)
安装
- 安装目录
set(CMAKE_INSTALL_PREFIX ${PROJECT_SOURCE_DIR}/install)
install(DIRECTORY ${PROJECT_SOURCE_DIR}/etc DESTINATION . PATTERN etc/*.json EXCLUDE)
install(FILES ${PROJECT_SOURCE_DIR}/README.md DESTINATION .)
cache 变量
normal variable: 普通变量,局部作用域
cache variable: 缓存变量,全局变量, 同一个CMAKE功能任何地方都可以用
set(
variable:变量名称
value:变量值列表
CACHE:cache变量的标志
type:变量类型,取决于变量的值。类型分为:BOOL、FILEPATH、PATH、STRING、INTERNAL
docstring:必须是字符串,作为变量概要说明
FORCE:强制选项,强制修改变量值