主要说明
平时在linux下编写编译脚本时,不是缺少这就是缺少那,管理起来很麻烦并且不同编译链换了兼容性不好。所以学习着写了一个编译模板。 主要是写三个文件CMakeList.txt、XXXX.cmake、make.sh,CMakeList.txt设置编译选项,设置包括的源文件、头文件、依赖的库文件,XXX.cmake设置编译链和编译选项,make.sh设置编译的输出路径和具体编译选项链设置。
主要目录树结构:
build—编译输出目录
inc-----头文件目录
src----代码源文件
CMakeList.txt 文件
main.cpp 主要源文件
make.sh 执行脚本
首先CMakeList.txt文件:
cmake_minimum_required(VERSION 3.7) #检查编译cmake版本
project(demo)#工程名称
set(CMAKE_CXX_STANDARD 11)
#set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIC")
#set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
option(DEBUG "is debug" OFF) #设置编译开关
if(DEBUG)
add_definitions("-DEBUG")
endif(DEBUG)
include_directories( #设置编译依赖的源文件和头文件
"${CMAKE_CURRENT_SOURCE_DIR}/src"
"${CMAKE_CURRENT_SOURCE_DIR}/inc"
)
set(
SOURCE_FILES #设置编译依赖源文件
${CMAKE_CURRENT_SOURCE_DIR}/main.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/xxx.cpp
)
message("${SOURCE_FILES}")
add_executable(demo ${SOURCE_FILES}) #生成可执行的文件
target_link_libraries( #链接编译需要的库
demo
${CMAKE_CURRENT_SOURCE_DIR}/lib/libxxx.so
)
编译运行的脚本make.sh
#!/bin/bash
BUILD_DIR=build
if [ "$1" = "clean" ]; then
rm -rf "$BUILD_DIR" sample_demo
exit 0
fi
rm -rf "$BUILD_DIR"
# clean last builed
echo "Make HorWord $*..."
CMAKE_OPTS="-DCMAKE_TOOLCHAIN_FILE=./arm-none-linux-toolchain.cmake"
mkdir -p build
cd build
echo "CMAKE_OPTS: $CMAKE_OPTS"
cmake $CMAKE_OPTS \
-DCMAKE_VERBOSE_MAKEFILE=ON \
-DDEBUG=OFF \
../
make
echo "output_dir:$build"
cd ../
arm-none-linux-toolchain.cmake文件
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR arm)
set(CROSS_COMPILING_ROOT /usr/local/share/arm-none-linux-gnueabihf/bin)
SET(CMAKE_C_COMPILER arm-none-linux-gnueabihf-gcc)
SET(CMAKE_CXX_COMPILER arm-none-linux-gnueabihf-g++)
if(NOT DEFINED CROSS_COMPILING_ROOT)
set(CROSS_COMPILING_ROOT $ENV{CROSS_COMPILING_ROOT})
endif()
if(NOT DEFINED CROSS_COMPILING_ROOT)
message(FATAL_ERROR "Missing CROSS_COMPILING_ROOT")
elseif(NOT IS_DIRECTORY ${CROSS_COMPILING_ROOT})
message(FATAL_ERROR "CROSS_COMPILING_ROOT is not directory: ${CROSS_COMPILING_ROOT}")
endif()
set(CMAKE_FIND_ROOT_PATH ${CROSS_COMPILING_ROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY BOTH)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
UNSET(CMAKE_CXX_FLASS CACHE)
UNSET(CMAKE_C_FLASS CACHE)
set(SYSTEM_DETAILS arm-none-linux)
每次添加库文件时就在依赖的库文件后添加一行就可以了。如果新增源文件或者头文件就在依赖的头文件添加一行。