1 // 工程名
2 PROJECT (HELLO)
3
4 // 设置变量
5 SET(SRC_LIST main.c)
6
7 // 打印变量
8 MESSAGE(STATUS "This is BINARY dir " ${PROJECT_BINARY_DIR})
9 MESSAGE(STATUS "This is SOURCE dir "${HELLO_SOURCE_DIR})
10
11 // 生成可执行程序
12 ADD_EXECUTABLE(hello SRC_LIST)
13 // 生成库
14 add_library(hello static ${LIB_SRC_LIST})
15 add_library(hello shared ${LIB_SRC_LIST})
16
17 // 向当前工程添加存放源文件的子目录,并把中间文件、目标文件放在bin目录里
18 add_subdirectory(src bin)
19
20 // 指定最终的目标位置,不包括中间文件
21 set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/../bin)
22 set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/../lib)
23
24 // 指定头文件搜索路径
25 include_directories(lib)
26 // 添加库搜索路径
27 link_directories(lib)
28
29 // 添加库
30 target_link_libraries(main hello)
31 target_link_libraries(main libhello.so)
32
33 // 查找库
34 bash 中设置如下
35 export CMAKE_INCLUDE_PATH = ./include
36 export CMAKE_LIBRARY_PATH = ./lib
37
38 include_directories(/usr/include/hello)可以替换为
39 find_path(MyHeader hello.h)
40 if(not MyHeader)
41 include_directories(${MyHeader})
42 message(fatal_error "header not found")
43 endif(MyHeader)
44
45 // 增加宏定义
46 add_definitions(-DDEBUG -DWL_DEBUG)
47
48 // 增加依赖,确保在编译本target前,其他target已经编译过
49 add_dependencies(target_name depend_target1 depend_target2)
50
51 // 增加make test
52 add_test(test_name exename arg1 arg2 )
53 enable_testing()
54
55
56
57 备注:
58 1. 推荐外部构建,因为cmake不会生成make distclean, 没有办法清理生成中间文件。
59 如:在build目录中执行cmake ..
60 2. 指定目标的生成目录,add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL]),
61 EXCLUDE_FROM_ALL表示把目录从编译过程中排除
62 3. SUBDIRS(DIR1, DIR2...)已经不推荐使用, 在build目录下生成DIR1, DIR2, 每个工程的
63 中间文件都再各自的目录
64 4. 设置EXECUTABLE_OUTPUT_PATH\LIBRARY_OUTPUT_PATH可以在根目录和子目录中,但原则上放
65 在子目录
66 5. add_library不能生成一个名字的动态库、静态库(libhello.so libhello.a),需设置输出的名字
67 set_target_properties(hello_static properties output_name "hello")
68 6. 每次生成新的target时,会尝试清除使用这个名字的库,需要设置
69 set_target_properties(hello_static properties clean_direct_output 1)
70
71 警告:
72 1. CMake Warning (dev) in CMakeLists.txt:
73 No cmake_minimum_required command is present. A line of code such as
74 cmake_minimum_required(VERSION 2.8)
75 根据提示,在顶层的cmakelist中添加上面的命令
76
77 2. CMake Warning (dev) at NetModule/CMakeLists.txt:8 (link_directories):
78 This command specifies the relative path
79 ../ACE/6.0.1/ACE_wrappers/lib/x64
80 根据cmake --help-policy CMP0015知道,OLD的行为是直接传递相对路径给链接器,NEW的行为是
81 在相对路径前面添加CMAKE_CURRENT_SOURCE_DIR变成一个绝对路径,然后传递给链接器。采用
82 cmake_policy(SET CMP0015 NEW)好些
83
84 cmake .. -G"Unix Makefiles"