目录
[如果这篇文章能帮助到你,请点个赞鼓励一下吧ξ( ✿>◡❛)~](#如果这篇文章能帮助到你,请点个赞鼓励一下吧ξ( ✿>◡❛)~)
CMakeLists.txt文件,是配置CAMKE工程的起点,
文件中的相关指令:
1、指定CMAKE最低的版本号
cpp
cmake_minimum_required(VERSION 3.15)
2、设置工程名
cpp
project(Tutorial)
3、添加可执行文件
cpp
add_executable(Tutorial tutorial.cpp)
4、简化项目名的表示
cpp
add_executable(${PROJECT_NAME} tutorial.cpp)
(其中${PROJECT_NAME}表示PROJECT_NAME该值为宏定义替换)
5、添加多个可执行文件
cpp
add_executable(${PROJECT_NAME} a.cpp b.cpp c.cpp)
#多个可执行文件之间使用 空格 隔开
6、添加多个可执行文件的简洁方法
cpp
set(SRC_LIST a.cpp b.cpp c.cpp)
add_executable(${PROJECT_NAME} ${SRC_LIST})
#使用SRC_LIST来指代多个可执行文件,SRC_LIST就是多个文件名的宏定义
7、添加版本号和配置头文件
cpp
project(Tutorial VERSION 1.0.2)
#这个命令为项目增加了一个版本号
8、指定C++版本
cpp
cmake_minimum_required(VERSION 3.15)
# set the project name and version
project(${PROJECT_NAME} VERSION 1.0)
# specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
#当gcc版本>6.1,不显式指定C++版本,默认C++版本为C++14,其中CMAKE_CXX_STANDARD变量就是指定C++本版的宏
9、添加库
cpp
# MathFunctions/CMakeLists.txt
add_library(MathFunctions mysqrt.cpp)
#在MathFunctions目录包含两个文件,MathFunctions.h 和 mysqrt.cpp,在这个目录下创建一个CMakeLists.txt文件,内容如上所示,表示添加一个叫MathFunctions的库文件
10、使用库
cpp
add_subdirectory(MathFunctions)
#为了使用MathFunctions库,需要在顶层的CMakeLists.txt文件中添加上述命令,指定库所在的子目录,该子目录下包含CMakeLists.txt文件和头文件、源文件。
# add the MathFunctions library
add_subdirectory(MathFunctions)
# add the executable
add_executable(${PROJECT_NAME} tutorial.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC MathFunctions)
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(${PROJECT_NAME} PUBLIC
${PROJECT_BINARY_DIR}
${PROJECT_SOURCE_DIR}/MathFunctions
)
11、将库设置为可选项
cpp
if(USE_MYMATH)
add_subdirectory(MathFunctions)
list(APPEND EXTRA_LIBS MathFunctions)
list(APPEND EXTRA_INCLUDES ${PROJECT_SOURCE_DIR}/MathFunctions)
endif()
# add the executable
add_executable(${PROJECT_NAME} tutorial.cpp)
target_link_libraries(${PROJECT_NAME} PUBLIC ${EXTRA_LIBS})
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
target_include_directories(${PROJECT_NAME} PUBLIC
${PROJECT_BINARY_DIR}
${EXTRA_INCLUDES}
)
#将库设置为可选项,可以在不使用库时,将库文件从编译过程中剥离出去,优化编译效率和代码体积。