注:本人的临时记录,没什么参看价值,可移步https://cmake.org/cmake/help/v3.21/guide/tutorial/index.html
1. 概述
用CMake构建一个简单的项目,项目由一个exe以及一个dll组成,项目目录结构如上图,build_MyHello是编译生成的目录。项目包含ALL_BUILD,RUN_TEST,INSTALL,PACKAGE,如下图:
2. 详细步骤
-
MyHello/CMakeLists.txt
add_subdirectory:将src目录加入编译,CMake会去src目录下找CMakeLists.txt。我在MyHello/src/CMakeLists.txt中使用了add_executable来编译一个exe。当让也可以直接在以下CMakeLists.txt中直接写add_executable,只是处理好路径即可,但在子目录中各自管理自己的CMakeLists.txt会更清晰些。cmake_minimum_required(VERSION 3.21) PROJECT(Hello VERSION 2.0)# 测试打印信息功能 MESSAGE(STATUS "hello, this is cmake message") MESSAGE(STATUS ${PROJECT_BINARY_DIR}) MESSAGE(STATUS ${Hello_VERSION_MAJOR})# 将src目录加入到编译中 add_subdirectory(src)# 加入测试 enable_testing() add_test(NAME Runs COMMAND MyHelloExe ) add_test(NAME Usage COMMAND MyHelloExe )# 加入打包功能 include(InstallRequiredSystemLibraries) set(CPACK_PACKAGE_VERSION_MAJOR "${Hello_VERSION_MAJOR}") set(CPACK_PACKAGE_VERSION_MINOR "${Hello_VERSION_MINOR}") include(CPack)
-
MyHello/src/CMakeLists.txt
# 打印信息 MESSAGE( STATUS ${PROJECT_SOURCE_DIR} )# set(CMAKE_CXX_STANDARD 11) # set(CMAKE_CXX_STANDARD_REQUIRED True)# 设置选项 option(USE_MYMATH "Use my maths" ON)if( USE_MYMATH )# 将Maths文件夹加入编译add_subdirectory(Maths)list(APPEND EXTRA_LIBS MyMath)list(APPEND EXTRA_INCLUDES ${PROJECT_SOURCE_DIR}/Maths) endif()# 生成一个exe add_executable(MyHelloExe main.cpp)# 生成my_header.h文件,my_header.h.out中宏会被替换 configure_file(my_header.h.out my_header.h)# 依赖的lib, target_link_directories可用来增加库目录 target_link_libraries(MyHelloExe PUBLIC ${EXTRA_LIBS})# 头文件包含目录 target_include_directories(MyHelloExe PUBLIC ${PROJECT_BINARY_DIR}/src ${EXTRA_INCLUDES} )# 测试加入预编译宏 target_compile_definitions(MyHelloExe PRIVATE "HAVE_LOG" "HAVE_EXP")# 安装 install(TARGETS MyHelloExe DESTINATION bin) install(FILES "${PROJECT_BINARY_DIR}/src/my_header.h" DESTINATION include )
-
MyHello/src/main.cpp
#include <iostream> #include "my_header.h"int main(int argc, char** argv) {std::cout << "hello world" << std::endl;std::cout << "Version Main is " << Hello_VERSION_MAJOR << std::endl;std::cout << "Version Minor is " << Hello_VERSION_MINOR << std::endl;#ifdef USE_MYMATHstd::cout << "use my math" << std::endl; #endifreturn 0; }
-
MyHello/src/my_header.h.out
一般会命名成my_header.h.in#define Hello_VERSION_MAJOR @Hello_VERSION_MAJOR@ //CMake的内置变量:<PROJECT-NAME>_VERSION_MAJOR #define Hello_VERSION_MINOR @Hello_VERSION_MINOR@ //CMake的内置变量:<PROJECT-NAME>_VERSION_MINOR #cmakedefine USE_MYMATH
-
MyHello/src/Maths/CMakeLists.txt
# 打印信息 message(STATUS "add Maths library")# 编译生成dll,不依赖其他库 add_library(MyMath SHARED mysqrt.cpp)# 安装 install(TARGETS MyMath LIBRARY DESTINATION lib) install(TARGETS MyMath RUNTIME DESTINATION bin) install(FILES mysqrt.h DESTINATION include)
-
MyHello/src/Maths/mysqrt.h
测试用,无内容 -
MyHello/src/Maths/mysqrt.cpp
#include "mysqrt.h"
3. 参看
https://cmake.org/cmake/help/v3.21/guide/tutorial/index.html