CMake工程开发入门笔记
CMake通过CMakeLists.txt生成makefile,对于含有大量文件的工程编译十分方便。
指令 | 解释 | 例 |
---|---|---|
PROJECT | 设定工程名(可与生成目标名不同),该指令隐式定义了<PROJECT_NAME>_BINARY_DIR和<PROJECT_NAME>_SOURCE_DIR | PROJECT(helloworld) |
SET | 设置变量 | SET(SRC_LIST main.c fun.c) |
MESSAGE | 打印消息 | MESSAGE(STATUS/SEDN_ERROR/FATAL_ERROR “todisplay” ) |
ADD_EXEUTABLE | 生成目标文件 | ADD_EXEUTABLE(your_exe main.c fun.c) |
ADD_LIBRARY | 生成动态库或静态库 | ADD_LIBRARY(your_lib_name STATIC/SHARED> ) |
SET_TARGET_PROPERTIES | 可用于同时生成.so和.lib,设置.so的版本号和api号 | NA |
ADD_SUBDIRECTORY | 添加包含源文件的子目录 | NA |
TARGET_LINK_LIBRARIES | 链接需要的library | TARGET_LINK_LIBRARIES(project_name lib***.so/***) TARGET_LINK_LIBRARIES(project_name ${GTEST_LIBRARY}) |
LINK_DIRECTORIES | 添加非标准的库搜索库搜索路径 | NA |
INCLUDE_DIRECTORIES | 添加头文件搜索路径 | (BEFORE {OpenCV_INCLUDE_DIRS}) BEFORE 添加的头文件搜索路径在默认路径的前面,反之AFTER |
INSTALL | 可以用于安装生成的可执行文件 .so .lib 和 .sh以及一般文件 | NA |
常见错误:
-
set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)
-
误用 LIBRARY_OUTPUT_DIRECTORY是无法设置输出路径的。 CMakeLists.txt 错误 写的.c文件,C++头文件make找不到,改成.cpp或cc
mkdir Project
cd Project
gedit CMakeLists.txt
mkdir src
cd src
touch main.c
vi main.c
:qw
mkdir build
cd build
gedit CMakeLists.txt
#CMAKE 常用外部构建,out-of-source, 举个例子,将构建过程放到build, 在buil的目录下 cmake ..
cmake ..
make -j
CMake进阶
Cross Compile
It is effective to have a cross compiling when debugging
Host PC: x86
Target: TX2 aarch64
sudo apt-get install g++-4.9-aarch64-linux-gnu
#Point out the target
set(CMAKE_SYSTEM_NAME Linux)
#Specify the cross compiler
#set(CMAKE_CXX_COMPILER /path/to/compiler)
set(CAME_CXX_COMPILER /usr/bin/aarch64-linux-gnu-g++)
# Just make sure you set the CMAKE_FIND_ROOT_PATH variable to a path where you have #an exact copy of the root filesystem you have on your target device (with libraries and binaries #pre-compiled for the target processor).
set(CMAKE_FIND_ROOT_PATH /path/to/copied root filesysem of target)
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
CMAKE_FIND_ROOT_PATH_MODE_PROGRAM sets the default behaviour for the FIND_PROGRAM() command. It can be set to NEVER, ONLY or BOTH (default). If set to NEVER, CMAKE_FIND_ROOT_PATH will not be used for FIND_PROGRAM() calls (except where it is enabled explicitely). If set to ONLY, only the search directories with the prefixes coming from CMAKE_FIND_ROOT_PATH will be used in FIND_PROGRAM(). The default is BOTH, which means that at first the prefixed directories and after that the unprefixed directories will be searched. In most cases FIND_PROGRAM() is used to search for an executable which will then be executed e.g. using EXECUTE_PROCESS() or ADD_CUSTOM_COMMAND(). So in most cases an executable from the build host is required, so usually set CMAKE_FIND_ROOT_PATH_MODE_PROGRAM to NEVER.
You can make above file to ba X.cmake, and use CMAKE_TOOLCHAIN_FILE
cd build
cmake -DCMAKE_TOOLCHAIN_FILE = ~/X.cmake ..