cmake简单用法
CMake是一个跨平台的编译工具,类似于automake
安装
# cd cmake-2.8.10.2
# ./bootstrap
# make
# make install
project
project(<projectname> [CXX] [C] [JAVA])
定义工程的名称的和支持的语言。这一行会引入两个变量(HELLO_BINARY_DIR 和 HELLO_SOURCE_DIR)
set
set(VAR[VALUE] [CACHE TYPE DOCSTRING [FORCE]])
显式的定义变量
set(SRC_LIST hello.c)
message
message([SEND_ERROR | STATUS | FATAL_ERROR] "message to display" ...)
向终端输出用户信息
- SATUS:输出信息
- SEND_ERROR:产生错误,生成过程被跳过
- FATAL_ERROR:立即终止所有cmake过程
message(STATUS "This is SOURCE dir" ${HELLO_SOURCE_DIR})
add_executable
add_executable(<name> [WIN32] [MACOSX_BUNDLE] [EXCLUDE_FROM_ALL]
source1 source2 ... sourceN)
使用给定的源文件,为工程引入一个可执行文件
add_executable(${PROJECT_NAME} ${SRC_LIST})
举例
project(hello C CXX)
set(SRC_LIST helloworld.c)
MESSAGE(STATUS "This is BINARY dir " ${HELLO_BINARY_DIR})
message(STATUS "This is SOURCE dir "${CMAKE_SOURCE_DIR})
add_executable(${PROJECT_NAME} ${SRC_LIST})
常用变量名
- PROJECT_NAME:PROJECT 指令定义的项目名称
- CMAKE_SOURCE_DIR/PROJECT_SOURCE_DIR:工程顶层目录
- CMAKE_CURRENT_LIST_FILE:这个变量的 CMakeLists.txt 的完整路径
- CMAKE_CURRENT_LIST_LINE:这个变量所在的行
- EXECUTABLE_OUTPUT_PATH/LIBRARY_OUTPUT_PATH:最终结果的存放目录
常用指令
include_directories:程序所需头文件的位置
include_directories("./include")
link_directories:程序所需库文件的位置
link_directories("./lib")
target_link_libraries:链接库名称
target_link_libraries(${PROJECT_NAME} pthread)
target_link_libraries(${PROJECT_NAME} -lzlog)
注:target_link_libraries要放到add_executable后面,不然报如下错误
CMake Error at CMakeLists.txt:11 (target_link_libraries):
Cannot specify link libraries for target "lwm2mclient" which is not built
by this project.
BUILD_SHARED_LIBS:生成的为动态库
SET(BUILD_SHARED_LIBS ON)
ADD_LIBRARY:定义生成的库的名字,以及类型和需要的源文件
ADD_LIBRARY(libname [SHARED|STATIC|MODULE] [EXCLUDE_FROM_ALL] source1 source2 ... sourceN)
ADD_LIBRARY(myhello ${SRC_LIST}) //名字不要冲突
# make
[ 50%] Built target hello
Scanning dependencies of target myhello
[100%] Building C object CMakeFiles/myhello.dir/helloworld.o
Linking C static library libmyhello.a
ADD_DEFINITIONS:添加-D定义。使#ifdef ENABLE_DEBUG生效
ADD_DEFINITIONS(-DENABLE_DEBUG ...)
ADD_TEST/ENABLE_TESTING:
ADD_TEST(testname exename arg1 arg2 ...)
ADD_TEST(mytest ./bin/hello)
ENABLE_TESTING()
AUX_SOURCE_DIRECTORY:临时构建源文件列表。发现一个目录下所有源代码文件并将列表存储在一个变量中
AUX_SOURCE_DIRECTORY(dir VARIABLE)
ADD_EXECUTABLE(${PROJECT_NAME} ${SRC_LIST})
CMAKE_MINIMUM_REQUIRED:版本限制
CMAKE_MINIMUM_REQUIRED(VERSION versionNumber [FATAL_ERROR])
CMAKE_MINIMUM_REQUIRED(VERSION 2.8 FATAL_ERROR)
INSTALL:make install使用
INSTALL(PROGRAMS bin/hello DESTINATION bin)
# cmake -DCMAKE_INSTALL_PREFIX=./demo/ .
# make install
Install the project...
-- Install configuration: ""
-- Installing: /home/thomas/demo/bin/hello
添加gdb调试
# cmake -DCMAKE_BUILD_TYPE=Debug .