编写CMakeLists.txt
#在当前目录新建一个build目录,然后cd build;cmake ..
#这样的好处是,可以将cmake生成的内容,和源码文件分离
#设置编译结果发布路径
set( CMAKE_INSTALL_PREFIX ./_install)
#配置一个头文件,可以让一些cmake设置传到源码里,比如可以传版本号,传宏定义等等
configure_file (
"${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
"${PROJECT_BINARY_DIR}/TutorialConfig.h"
)
#将可执行文件与其源码关联起来
add_executable(Tutorial tutorial.c)
#如果是很多源码,可以写一个变量,先把源码文件收集起来,比如下面这样,
set(SRC_FILES avl.c rb.c splay.c)
add_executable(Tutorial ${SRC_FILES})
#增加库文件
add_library(MathFunctions mysqrt.cxx)
#增加动态库,SRC_TREE_FILES是实现定义好的源码文件列表
add_library(tree SHARED ${SRC_TREE_FILES})
#增加静态库
add_library(tree_static STATIC ${SRC_TREE_FILES})
#将库文件和可执行文件链接起来
target_link_libraries (Tutorial MathFunctions)
#如何连接系统库,但是必须在add_executable之前加才有效
LINK_LIBRARIES(-lpthread -lm)
#验证系统是否提供某些函数
# does this system provide the log and exp functions?
include (CheckFunctionExists)
check_function_exists (log HAVE_LOG)
check_function_exists (exp HAVE_EXP)
#也还需要在配置文件TutorialConfig.h中增加,这样源码中就能用这个宏定义来确定函数是否支持
#cmakedefine HAVE_LOG
#cmakedefine HAVE_EXP
#可以增加头文件搜索路径
include_directories ("${PROJECT_BINARY_DIR}")
#或者为某一个目标添加
target_include_directories(os_demo
PRIVATE
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/inc
)
#如何添加编译选项; 设置编译选项可以通过add_compile_options命令,也可以通过set命令修改CMAKE_CXX_FLAGS或CMAKE_C_FLAGS
SET(CMAKE_C_FLAGS "-O3 -ffast-math -Wall -std=gnu99 -fPIC")
#疑问?
${CMAKE_CURRENT_BINARY_DIR},${PROJECT_SOURCE_DIR},${PROJECT_BINARY_DIR}在哪定义的
#通过打印显示;CMAKE_CURRENT_BINARY_DIR,PROJECT_BINARY_DIR是当前目录,PROJECT_SOURCE_DIR是CMakeLists.txt所在目录。
-- This is the engine CMAKE_CURRENT_BINARY_DIR: /home/xxxx/engine/build.tx1
-- This is the engine PROJECT_SOURCE_DIR: /home/xxxx/engine
-- This is the engine PROJECT_BINARY_DIR: /home/xxxx/build.tx1
#如何方便的进行交叉编译?一般要用到CMAKE_TOOLCHAIN_FILE
cmake .. -DCMAKE_TOOLCHAIN_FILE=../tx1.toolchain.cmake
#下面是一个简单的toolchain.cmake例子
# this is required
SET(CMAKE_SYSTEM_NAME Linux) # specify the cross compiler
SET(CMAKE_C_COMPILER /opt/nvidia/gcc-linaro-5.3.-2016.05-x86_64_aarch64-linux-gnu//bin/aarch64-linux-gnu-gcc)
SET(CMAKE_CXX_COMPILER /opt/nvidia/gcc-linaro-5.3.-2016.05-x86_64_aarch64-linux-gnu//bin/aarch64-linux-gnu-g++) # where is the target environment
SET(CMAKE_FIND_ROOT_PATH /opt/nvidia/gcc-linaro-5.3.-2016.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/include/c++/5.3.) # search for programs in the build host directories (not necessary)
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)