cmake 使用
1单文件编译
CMakeLists.txt:
# set minimum cmake version
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
# project name and language
project(recipe-01 LANGUAGES C)
add_executable(hello-world hello-world.c)
目录结构
-hello-world.c
-CMakeLists.txt
编译命令
cmake .# cmake命令默认将生成文件放在执行cmake命令的目
录,cmake+路径,该路径指明CMakeLists.txt所在目录
cmake --build . # 根据上步生成的文件,进一步生成makefile文件,--build后面的路径为上一步中的构建路径
#所以一般的操作是mkdir -p build;cd build;cmake ..;
#cmake -S /path/to/source -B /path/to/build
#-S指定源代码路径,-B指定构建路径
切换生成器, 默认在windows下使用时,使用的编译器是MSVC使用cl.exe来编译c程序的。要想配置mingw中的gcc,那么需要切换生成器为MinGW Makefiles
cmake --help #将列出CMake命令行界面上所有的选项,可找到可用生成器的列表
cmake -G Ninja .. #-G参数指定生成器,默认情况下cmake根据系统调用和系统匹配的生成器
cmake -G "MinGW Makefiles" # 指定使用mingw生成器,编译器也使用这个
2 多文件编译
同一个目录多文件编译
目录结构
-CMakeLists.txt
-hello-world.cpp
-Message.hpp
-Message.cpp
CMakeLists.txt:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(recipe-03 LANGUAGES CXX)
方法1:add_executable(Demo hello-world.cpp Message.hpp Message.cpp)
方法2:set(SRC_LIST hello-world.cpp Message.hpp Message.cpp)
add_executable(Demo ${SRC_LIST})
方法3:file(GLOB_RECURSE ALL_SRCS *.cpp *.c) # 此处*.cpp *.c你可以再增加自己的路径,比如src/math/*.cpp *.c
add_executable(Demo ${ALL_SRCS})
方法4:aux_source_directory(. DIR_SRCS)# 查找当前目录下的所有源文件,并将名称保存到 DIR_SRCS 变量
add_executable(Demo ${DIR_SRCS})
方法5:add_library(Demo_lib Message.hpp Message.cpp)
add_executable(Demo main.c)
target_link_libraries(Demo Demo_lib)
不同目录多文件编译
目录结构
├── CMakeLists.txt
├── main.cpp
└── math
├── CMakeLists.txt
├── myMath.cpp
└── myMath.h
根目录下的CMakeLists.txt:
cmake_minimum_required (VERSION 2.8)
project (demo3)
add_subdirectory(math)
add_executable(demo main.cpp)
target_link_libraries(demo MathFunctions)
子目录中的CMakeLists.txt: //相当于替换根目录下的CMakeLists.txt中的add_subdirectory那行
aux_source_directory(. DIR_LIB_SRCS)
add_library(MathFunctions ${DIR_LIB_SRCS})
目录结构
├── CMakeLists.txt
├── main.cpp
└── math
├── myMath.cpp
└── myMath.h
根目录下的CMakeLists.txt:
cmake_minimum_required (VERSION 2.8)
project (demo3)
file(GLOB_RECURSE ALL_SRCS math/*.cpp) # 此处*.cpp *.c你可以再增加自己的路径,比如src/math/*.cpp *.c
add_executable(Demo main.cpp ${ALL_SRCS})
或者
aux_source_directory(math DIR_SRCS)
add_executable(Demo main.cpp ${DIR_SRCS})
或者
add_executable(Demo main.cpp math/myMath.cpp)