CMake Tutorial Step 2
原文链接: Step 2: Adding a Library
1. 在次级目录里构建自定义库
-
- Cmakelist 只需要一句话
add_library(MathFunctions mysqrt.cxx)
- Cmakelist 只需要一句话
2. 在顶层目录中添加次级文件夹
-
- CMakeList 中添加
这通过 add_subdirectory 直接把次级文件夹中内容在当前目录里构建了# add the MathFunctions library add_subdirectory(MathFunctions) # add the executable add_executable(Tutorial tutorial.cxx) target_link_libraries(Tutorial PUBLIC MathFunctions) # add the binary tree to the search path for include files # so that we will find TutorialConfig.h target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}" "${PROJECT_SOURCE_DIR}/MathFunctions" )
所以可以直接使用次级文件夹构建出的库 MathFunctions
- CMakeList 中添加
-
- 把次级文件夹设置为可选项
通过添加宏来控制,默认是 ON ,可以在编译选项里修改option(USE_MYMATH "Use tutorial provided math implementation" ON) # configure a header file to pass some of the CMake settings # to the source code configure_file(TutorialConfig.h.in TutorialConfig.h)
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(Tutorial tutorial.cxx) target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS}) # add the binary tree to the search path for include files # so that we will find TutorialConfig.h target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}" ${EXTRA_INCLUDES} )
- 把次级文件夹设置为可选项
-
- 把 USE_MYMATH 传入到 cpp 里
在 TutorialConfig.h.in 中添加
#cmakedefine USE_MYMATH
这样生成的 .h 里会多一个宏// the configured options and settings for Tutorial #define Tutorial_VERSION_MAJOR 1 #define Tutorial_VERSION_MINOR 0 #define USE_MYMATH
- 把 USE_MYMATH 传入到 cpp 里
-
- 取消 USE_MYMATH
直接编译选项里设置
cmake ../Step2 -DUSE_MYMATH=OFF
这会让 CMakeList 里的 USE_MYMATH 变为 OFF
并且 .h 中的相关 define 直接被注释掉// the configured options and settings for Tutorial #define Tutorial_VERSION_MAJOR 1 #define Tutorial_VERSION_MINOR 0 /* #undef USE_MYMATH */
- 取消 USE_MYMATH