CMake 基础
CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程)。 他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的automake。 只是 CMake 的组态档取名为 CMakeLists.txt。 Cmake 并不直接建构出最终的软件,而是产生标准的建构档(如 Unix 的 Makefile 或 Windows Visual C++ 的 projects/workspaces),然后再依一般的建构方式使用。 这使得熟悉某个集成开发环境(IDE)的开发者可以用标准的方式建构他的软件,这种可以使用各平台的原生建构系统的能力是 CMake 和 SCons 等其他类似系统的区别之处。
构建系统
binary target
add_library(name sources)
add_executable(name sources)
target_link_libraries(name archive)
可执行文件
add_executable(name sources)
库文件
add_library(name SHARED sources) # 共享库
add_library(name STATIC sources) # 静态库
add_library(name MODULE sources)
## Apple framework
add_library(MyFramework SHARED MyFramework.cpp)
set_target_properties(MyFramework PROPERTIES
FRAMEWORK TRUE
FRAMEWORK_VERSION A # Version "A" is macOS convention
MACOSX_FRAMEWORK_IDENTIFIER org.cmake.MyFramework
)
## Object libraries
add_library(archive OBJECT archive.cpp zip.cpp lzma.cpp)
add_library(archiveExtras STATIC $<TARGET_OBJECTS:archive> extras.cpp)
add_executable(test_exe $<TARGET_OBJECTS:archive> test.cpp)
## Using target_link_libraries
add_library(archive OBJECT archive.cpp zip.cpp lzma.cpp)
add_library(archiveExtras STATIC extras.cpp)
target_link_libraries(archiveExtras PUBLIC archive)
add_executable(test_exe test.cpp)
target_link_libraries(test_exe archive)
使用要求
target_include_directories()
target_compile_definitions()
target_compile_options()
include_directories()
compile_definitions()
compile_options()
接口兼容属性
add_executable(exe1 exe1.cpp)
set_property(TARGET exe1 PROPERTY POSITION_INDEPENDENT_CODE ON)
alias
add_library(xxxx ALIAS libx)
Commands
Scripting Commands
break
cmake_host_system_information
cmake_language
cmake_minimum_required
cmake_parse_arguments
cmake_policy
configure_file
continue
else
elseif
endforeach
endfunction
endif
endmacro
endwhile
execute_process
file
find_file
find_library
find_package
find_path
find_program
foreach
function
get_cmake_property
get_directory_property
get_filename_component
get_property
if
include
include_guard
list
macro
mark_as_advanced
math
message
option
return
separate_arguments
set
set_directory_properties
set_property
site_name
string
unset
variable_watch
while
Project Commands
add_compile_definitions
add_compile_options
add_custom_command
add_custom_target
add_definitions
add_dependencies
add_executable
add_library
add_link_options
add_subdirectory
add_test
aux_source_directory
build_command
create_test_sourcelist
define_property
enable_language
enable_testing
export
fltk_wrap_ui
get_source_file_property
get_target_property
get_test_property
include_directories
include_external_msproject
include_regular_expression
install
link_directories
link_libraries
load_cache
project
remove_definitions
set_source_files_properties
set_target_properties
set_tests_properties
source_group
target_compile_definitions
target_compile_features
target_compile_options
target_include_directories
target_link_directories
target_link_libraries
target_link_options
target_precompile_headers
target_sources
try_compile
try_run
CTest Commands
ctest_build
ctest_configure
ctest_coverage
ctest_empty_binary_directory
ctest_memcheck
ctest_read_custom_files
ctest_run_script
ctest_sleep
ctest_start
ctest_submit
ctest_test
ctest_update
ctest_upload
编译特性
add_library(mylib requires_constexpr.cpp)
target_compile_features(mylib PRIVATE cxx_constexpr) ## 特性需求
target_compile_features(mylib PUBLIC cxx_std_11) ## 标准需求
Find Modules
变量
# FindXxxx.cmake
Xxx_INCLUDE_DIRS
Xxx_LIBRARIES
Xxx_DEFINITIONS
Xxx_EXECUTABLE
Xxx_Yyy_EXECUTABLE #
Xxx_LIBRARY_DIRS
Xxx_ROOT_DIR
Xxx_VERSION_Yy
Xxx_WRAP_Yy
Xxx_Yy_FOUND
Xxx_FOUND
Xxx_NOT_FOUND_MESSAGE
Xxx_RUNTIME_LIBRARY_DIRS
Xxx_VERSION
Xxx_VERSION_MAJOR
Xxx_VERSION_MINOR
Xxx_VERSION_PATCH
Xxx_LIBRARY
Xxx_Yy_LIBRARY
Xxx_INCLUDE_DIR
Xxx_Yy_INCLUDE_DIR
find module Sample
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
#[=======================================================================[.rst:
FindFoo
-------
Finds the Foo library.
Imported Targets
^^^^^^^^^^^^^^^^
This module provides the following imported targets, if found:
``Foo::Foo``
The Foo library
Result Variables
^^^^^^^^^^^^^^^^
This will define the following variables:
``Foo_FOUND``
True if the system has the Foo library.
``Foo_VERSION``
The version of the Foo library which was found.
``Foo_INCLUDE_DIRS``
Include directories needed to use Foo.
``Foo_LIBRARIES``
Libraries needed to link to Foo.
Cache Variables
^^^^^^^^^^^^^^^
The following cache variables may also be set:
``Foo_INCLUDE_DIR``
The directory containing ``foo.h``.
``Foo_LIBRARY``
The path to the Foo library.
#]=======================================================================]
find_path(Foo_INCLUDE_DIR NAMES xxx.h PATHS ${xxxx} PATH_SUFFIXES Foo)
find_library(Foo_LIBRARY NAMES foo PATHS ${XXXXX})
set(Foo_VERSION xxxx)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Foo
FOUND_VAR Foo_FOUND
REQUIRED_VARS
Foo_LIBRARY
Foo_INCLUDE_DIR
VERSION_VAR Foo_VERSION
) ## check requeired vars
Usage
find_package(Foo)
if(Foo_FOUND)
set(FOO_LIBRARY $(Foo_LIBRARY))
endif()
cmake env variables
change behavior
CMAKE_PREFIX_PATH
控制构建
CMAKE_APPLE_SILICON_PROCESSOR
CMAKE_BUILD_PARALLEL_LEVEL
CMAKE_CONFIG_TYPE
CMAKE_EXPORT_COMPILE_COMMANDS
CMAKE_GENERATOR
CMAKE_GENERATOR_INSTANCE
CMAKE_GENERATOR_PLATFORM
CMAKE_GENERATOR_TOOLSET
CMAKE_<LANG>_COMPILER_LAUNCHER
CMAKE_MSVCIDE_RUN_PATH
CMAKE_NO_VERBOSE
CMAKE_OSX_ARCHITECTURES
DESTDIR
LDFLAGS
MACOSX_DEPLOYMENT_TARGET
<PackageName>_ROOT
VERBOSE
语言
ASM<DIALECT>
ASM<DIALECT>FLAGS
CC
CFLAGS
CSFLAGS
CUDACXX
CUDAFLAGS
CUDAHOSTCXX
CXX
CXXFLAGS
FC
FFLAGS
ISPC
ISPCFLAGS
OBJC
OBJCXX
RC
RCFLAGS
SWIFTC
ctest
CMAKE_CONFIG_TYPE
CTEST_INTERACTIVE_DEBUG_MODE
CTEST_OUTPUT_ON_FAILURE
CTEST_PARALLEL_LEVEL
CTEST_PROGRESS_OUTPUT
CTEST_USE_LAUNCHERS_DEFAULT
DASHBOARD_TEST_FROM_CTEST
表达式
## Logical
$<BOOL:string> # 转换String -> Bool
$<AND:conditions> # And Condition
$<OR:conditions> # Or
#<NOT:condition> $ Not
## String
$<STREQUAL:str1,str2> # 比较
$<EQUAL:value1,value2> # 数值比较
$<IN_LIST:string,list> #
$<VERSION_LESS:v1,v2>
$<VERSION_GREATER:v1,v2>
$<VERSION_EQUAL:v1,v2>
$<VERSION_LESS_EQUAL:v1,v2>
$<VERSION_GREATER_EQUAL:v1,v2>
$<JOIN:list,string>
$<REMOVE_DUPLICATES:list>
$<LOWER_CASE:string>
$<UPPER_CASE:xxx>
$<GENEX_EVAL:expr>
$<TARGET_GENEX_EVAL:tgt,expr>
## condition
$<condition:true_string>
$<IF:condition,true_string,false_string>
生成器
Makefile
Ninja
Visual Studio
XCode
CodeBlocks, Sublime Text 2, …
Language
CMakeLists.txt
script.cmake
module.cmake
Argument
'[=[' arg... ']=]' # 等于号任意多, 开始结束要一样
"arg..." # 引号
arg...
Variable
${VAR}
${VAR_${IN_VAR}_OP}
Comments
#[=*[ xxxx ]=*] 开始-结束标志的注释
# 单行注释
控制结构
condition
if()
elseif()
else()
endif()
loops
foreach()
endforeach()
while()
endwhile()
Variables
set()
unset()
Environment Variables
#{ENV{var}}
Lists
# Although all values in CMake are stored as strings,
# a string may be treated as a list in certain contexts,
# such as during evaluation of an Unquoted Argument.
set(srcs a.c b.c c.c) # sets "srcs" to "a.c;b.c;c.c"
set(x a "b;c") # sets "x" to "a;b;c", not "a;b\;c"
modules
include() command modules
AddFileDependencies
AndroidTestUtilities
BundleUtilities
CheckCCompilerFlag
CheckCompilerFlag
CheckCSourceCompiles
CheckCSourceRuns
CheckCXXCompilerFlag
CheckCXXSourceCompiles
CheckCXXSourceRuns
CheckCXXSymbolExists
CheckFortranCompilerFlag
CheckFortranFunctionExists
CheckFortranSourceCompiles
CheckFortranSourceRuns
CheckFunctionExists
CheckIncludeFileCXX
CheckIncludeFile
CheckIncludeFiles
CheckIPOSupported
CheckLanguage
CheckLibraryExists
CheckLinkerFlag
CheckOBJCCompilerFlag
CheckOBJCSourceCompiles
CheckOBJCSourceRuns
CheckOBJCXXCompilerFlag
CheckOBJCXXSourceCompiles
CheckOBJCXXSourceRuns
CheckPIESupported
CheckPrototypeDefinition
CheckSourceCompiles
CheckSourceRuns
CheckStructHasMember
CheckSymbolExists
CheckTypeSize
CheckVariableExists
CMakeAddFortranSubdirectory
CMakeBackwardCompatibilityCXX
CMakeDependentOption
CMakeFindDependencyMacro
CMakeFindFrameworks
CMakeFindPackageMode
CMakeGraphVizOptions
CMakePackageConfigHelpers
CMakePrintHelpers
CMakePrintSystemInformation
CMakePushCheckState
CMakeVerifyManifest
CPack
CPackComponent
CPackIFW
CPackIFWConfigureFile
CSharpUtilities
CTest
CTestCoverageCollectGCOV
CTestScriptMode
CTestUseLaunchers
Dart
DeployQt4
Documentation
ExternalData
ExternalProject
FeatureSummary
FetchContent
FindPackageHandleStandardArgs
FindPackageMessage
FortranCInterface
GenerateExportHeader
GetPrerequisites
GNUInstallDirs
GoogleTest
InstallRequiredSystemLibraries
ProcessorCount
SelectLibraryConfigurations
SquishTestScript
TestBigEndian
TestForANSIForScope
TestForANSIStreamHeaders
TestForSSTREAM
TestForSTDNamespace
UseEcos
UseJava
UseJavaClassFilelist
UseJavaSymlinks
UseSWIG
UsewxWidgets
WriteCompilerDetectionHeader
find_package module
FindALSA
FindArmadillo
FindASPELL
FindAVIFile
FindBacktrace
FindBISON
FindBLAS
FindBoost
FindBullet
FindBZip2
FindCABLE
FindCoin3D
FindCUDAToolkit
FindCups
FindCURL
FindCurses
FindCVS
FindCxxTest
FindCygwin
FindDart
FindDCMTK
FindDevIL
FindDoxygen
FindEnvModules
FindEXPAT
FindFLEX
FindFLTK
FindFLTK2
FindFontconfig
FindFreetype
FindGCCXML
FindGDAL
FindGettext
FindGIF
FindGit
FindGLEW
FindGLUT
FindGnuplot
FindGnuTLS
FindGSL
FindGTest
FindGTK
FindGTK2
FindHDF5
FindHg
FindHSPELL
FindHTMLHelp
FindIce
FindIconv
FindIcotool
FindICU
FindImageMagick
FindIntl
FindITK
FindJasper
FindJava
FindJNI
FindJPEG
FindKDE3
FindKDE4
FindLAPACK
FindLATEX
FindLibArchive
FindLibinput
FindLibLZMA
FindLibXml2
FindLibXslt
FindLTTngUST
FindLua
FindLua50
FindLua51
FindMatlab
FindMFC
FindMotif
FindMPEG
FindMPEG2
FindMPI
FindODBC
FindOpenACC
FindOpenAL
FindOpenCL
FindOpenGL
FindOpenMP
FindOpenSceneGraph
FindOpenSSL
FindOpenThreads
Findosg
Findosg_functions
FindosgAnimation
FindosgDB
FindosgFX
FindosgGA
FindosgIntrospection
FindosgManipulator
FindosgParticle
FindosgPresentation
FindosgProducer
FindosgQt
FindosgShadow
FindosgSim
FindosgTerrain
FindosgText
FindosgUtil
FindosgViewer
FindosgVolume
FindosgWidget
FindPatch
FindPerl
FindPerlLibs
FindPHP4
FindPhysFS
FindPike
FindPkgConfig
FindPNG
FindPostgreSQL
FindProducer
FindProtobuf
FindPython
FindPython2
FindPython3
FindQt3
FindQt4
FindQuickTime
FindRTI
FindRuby
FindSDL
FindSDL_image
FindSDL_mixer
FindSDL_net
FindSDL_sound
FindSDL_ttf
FindSelfPackers
FindSquish
FindSQLite3
FindSubversion
FindSWIG
FindTCL
FindTclsh
FindTclStub
FindThreads
FindTIFF
FindUnixCommands
FindVTK
FindVulkan
FindWget
FindWish
FindwxWidgets
FindX11
FindXalanC
FindXCTest
FindXercesC
FindXMLRPC
FindZLIB