CMake边用边学

CMake官网

我觉得CMake当个工具用,用到的时候边查边用,临时抱佛脚也来得及。

简单示例:

# 指定工程名
PROJECT (HELLO)
# 现阶段,你只需要了解 SET 指令可以用来显式的定义变量即可
# 将 hello.cpp 赋值给 SRC_LIST 变量,也可以指定多个源文件,用空格隔开
# SET(SRC_LIST hello.cpp add.cpp sub.cpp)
SET(SRC_LIST hello.cpp)
# 输出打印构建目录
MESSAGE(STATUS "This is HELLO_BINARY_DIR " ${HELLO_BINARY_DIR})
# 输出打印资源目录
MESSAGE(STATUS "This is HELLO_SOURCE_DIR " ${HELLO_SOURCE_DIR})
# 输出打印资源目录,与HELLO_SOURCE_DIR 一样 
MESSAGE(STATUS "This is PROJECT_SOURCE_DIR " ${PROJECT_SOURCE_DIR})
# 输出打印 CMake 资源目录,与 PROJECT_SOURCE_DIR 一样 
MESSAGE(STATUS "This is CMAKE_SOURCE_DIR " ${CMAKE_SOURCE_DIR})
# 生成可执行文件 hello ,${SRC_LIST}是引用变量,也就是源文件 hello.cpp
ADD_EXECUTABLE(hello ${SRC_LIST})
  • 一些参考:

CMake 语法 – 详解 CMakeLists.txt

使用CMake构建C++项目

使用 cmake 进行交叉编译

 

  • 迭代改进中:
cmake_minimum_required(VERSION 2.8.12)

project(robot)

MESSAGE(STATUS "operation system is ${CMAKE_SYSTEM}")

#SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -m32")
#SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -m32")

IF (CMAKE_SYSTEM_NAME MATCHES "Linux")
MESSAGE(STATUS "current platform: Linux ")
ADD_DEFINITIONS(-D LINUX)
ELSEIF (CMAKE_SYSTEM_NAME MATCHES "Windows")
MESSAGE(STATUS "current platform: Windows")
ELSE ()
MESSAGE(STATUS "other platform: ${CMAKE_SYSTEM_NAME}")
ENDIF (CMAKE_SYSTEM_NAME MATCHES "Linux")

add_compile_options(-w)

IF (CMAKE_BUILD_TYPE STREQUAL "Debug")
add_compile_options(-O0 -g)
ELSEIF (CMAKE_BUILD_TYPE STREQUAL "Release")
add_compile_options(-O0)
ENDIF()
MESSAGE(STATUS "current build type: ${CMAKE_BUILD_TYPE}")

file(GLOB_RECURSE CURRENT_HEADERS *.h *.hpp)
source_group("Include" FILES ${CURRENT_HEADERS})

include_directories(
.
)

link_directories(
)

FILE (GLOB ALL_SOURCES "*.cpp")

add_executable(${PROJECT_NAME} ${ALL_SOURCES} ${CURRENT_HEADERS})

target_link_libraries(${PROJECT_NAME} -lpthread)

install(TARGETS ${PROJECT_NAME}
RUNTIME DESTINATION .
)
  • 使用方法:
mkdir build
cd build
cmake ..
make
make install
  • 使用 cmake 进行交叉编译

交叉编译,主要是设置一些环境变量。这些设定可以写成一个 .cmake 文件,1) 需要交叉编译时 include ,2)或者直接把这些配置写到 CMakeLists.txt 文件的开始位置。两种方法是等效的。
CMakeLists.txt包含.cmake文件

include (cross.cmake)

或者命令行指定cmake文件:

cmake path -DCMAKE_TOOLCHAIN_FILE=./toolchain.cmake

.cmake文件示例:

# this one is important
SET(CMAKE_SYSTEM_NAME Linux)
#this one not so much
SET(CMAKE_SYSTEM_VERSION 1)

# specify the cross compiler
SET(TOOLCHAIN_DIR "/home/robot/tools/gcc-linaro-arm-linux-gnueabihf-4.9-2014.07_linux/bin")
SET(CMAKE_C_COMPILER ${TOOLCHAIN_DIR}/arm-linux-gnueabihf-gcc)
SET(CMAKE_CXX_COMPILER ${TOOLCHAIN_DIR}/arm-linux-gnueabihf-g++)

# where is the target environment
SET(CMAKE_FIND_ROOT_PATH .)

# search for programs in the build host directories
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
# for libraries and headers in the target directories
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
Tags: