CMakeLists.txt 编写
记录下自己第一次编写的cmake.
- 一 目录结构如下:
. ├── CMakeLists.txt ├── include ├── judge ├── lib ├── Makefile ├── nvm_engine └── test
二级目录结构如下:
. ├── CMakeLists.txt ├── include │ └── db.hpp ├── judge │ ├── CMakeLists.txt │ ├── judge.cpp │ ├── performance.log │ ├── random.cpp │ ├── random.h │ └── README.md ├── lib ├── Makefile ├── nvm_engine │ ├── CMakeLists.txt │ ├── lib │ ├── NvmEngine.cpp │ ├── NvmEngine.hpp │ └── NvmEngine.o └── test ├── CMakeLists.txt ├── test.cpp └── test.sh
整个工程代码可以分为4部分, include 文件夹、nvm_engine 文件夹, test 文件夹, judge 文件夹
其中include放置基础依赖性代码, nvm_engine 生成一个lib库(libengine),test 负责生成一个可执行文件, 调用libengine, judge 与 test类似。
lib目录存放,nvm_engine 生成库文件 libengine。
- 二 编写的CmakeLists结构如下:
. ├── CMakeLists.txt │ ├── judge │ └── CMakeLists.txt │ ├── nvm_engine │ └── CMakeLists.txt │ └── test └── CMakeLists.txt
- 三 各个CmakeLists.txt 如下
主目录CmakeLists.txt:
cmake_minimum_required(VERSION 3.3) project(tair) set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED True) set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # 生成json文件, 供coc代码提示使用 set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -g -mavx2") # 编译选项 set(ROOT_DIR ${PROJECT_SOURCE_DIR}) # 定义根目录变量 set(LIB_DIR ${ROOT_DIR}/lib) # 定义库目录变量 # 公共依赖的目录 include_directories( ${ROOT_DIR} ${ROOT_DIR}/include ) # 链接依赖的目录 link_directories(${LIB_DIR}) #生成 libengine 库 的函数 function (lib_generator name) # include 当前目录 include_directories( ${ROOT_DIR}/nvm_engine ) # 指定库生成依赖的文件 file(GLOB_RECURSE LIB_SRC *.hpp *.cpp) # 生成库 add_library(${name} ${LIB_SRC}) # 指定链接依赖库 target_link_libraries(${name} pthread rt z pmem) # 设置库生成目录 set_target_properties(${name} PROPERTIES FOLDER "lib" ARCHIVE_OUTPUT_DIRECTORY ${LIB_DIR} RUNTIME_OUTPUT_DIRECTORY ${LIB_DIR} LIBRARY_OUTPUT_DIRECTORY ${LIB_DIR} ) endfunction() #test function (test_generator name) include_directories( ${ROOT_DIR}/${name} ) file(GLOB_RECURSE TEST_SRC *.hpp *.cpp) add_executable(${name} ${TEST_SRC}) target_link_libraries(${name} engine pthread rt z pmem) set(TEST_DIR ${ROOT_DIR}/${name}) set_target_properties(${name} PROPERTIES FOLDER "test" ARCHIVE_OUTPUT_DIRECTORY ${TEST_DIR} RUNTIME_OUTPUT_DIRECTORY ${TEST_DIR} LIBRARY_OUTPUT_DIRECTORY ${TEST_DIR} ) endfunction() add_subdirectory(nvm_engine) add_subdirectory(test) add_subdirectory(judge)
nvm_engine 下 CmakeLists.txt:
lib_generator("engine")
test下 CmakeLists.txt:
test_generator("test")
judege 下 CmakeLists.txt:
test_generator("judge")
- 四 主目录下增加Makefile, 便于一键执行
cmake: jsonfile cd build; cmake .. ; $(MAKE) jsonfile: mkdir -p build; if [ ! -f "compile_commands.json" ]; then ln -s build/compile_commands.json; fi clean: rm -rf build rm -rf test/test rm -rf judge/judge rm -rf lib/libengine.a rm -rf compile_commands.json