编写适用于多个平台的CMakeLists.txt

有时候你需要把一份代码分别编译到不同的平台运行, 比如我经常需要编译出xilinx zcu102开发板能够运行的程序, 也希望能够编译出一个x86的版本, 这就需要编写能够适用于多个平台的CMakeLists.txt, 可以根据传入的参数生成不同的版本。这方面的教程很多,我也没来得及深入研究cmake的跨平台CMakeLists.txt, 这里我只写出一个我能够使用的例子, 当做是记录方便以后查看。

cmake_minimum_required(VERSION 3.5)
project(ArmControlSystem)
set(CMAKE_CXX_STANDARD 11)
set(target armcontrolsystem)

set(source_file_list
fpga_net.cpp
fpga_keypoint.cpp
fpga_feature.cpp
fpga_resource.cpp
read_config.cpp
signal_control.cpp
socket.cpp
timer.cpp)

option(PLATFORM "arm64 or x86_64" arm64)
if (${PLATFORM} STREQUAL "arm64")
SET(CMAKE_SYSTEM_NAME Linux)
SET(CMAKE_FIND_ROOT_PATH "/data/Xilinx/zcu102_rv_ss/sw/sysroot")
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
SET(CMAKE_C_COMPILER "/data/Xilinx/SDK/2017.4/gnu/aarch64/lin/aarch64-linux/bin/aarch64-linux-gnu-gcc")
SET(CMAKE_CXX_COMPILER "/data/Xilinx/SDK/2017.4/gnu/aarch64/lin/aarch64-linux/bin/aarch64-linux-gnu-g++")
SET(CMAKE_BUILD_TYPE "Release")

include_directories(${CMAKE_FIND_ROOT_PATH}/usr/include ${CMAKE_FIND_ROOT_PATH}/usr/include/eigen3)
elseif (${PLATFORM} STREQUAL "x86_64")
SET(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS "-g")

find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
endif ()

set(install_root_dir /data/for_xilinx_zcu102/armcontrolsystem/${PLATFORM})
add_library(${target} SHARED ${source_file_list})
install(TARGETS ${target} LIBRARY DESTINATION ${install_root_dir}/lib)

install(FILES
fpga_net.h
fpga_keypoint.h
fpga_feature.h
fpga_resource.h
read_config.h
signal_control.h
socket.h
timer.h
DESTINATION ${install_root_dir}/include)

通过传入PLATFORM变量来确定目标平台, 编译出不同的版本:

arm64:  cmake -DPLATFORM=arm64 .. && make"
x86_64: cmake -DPLATFORM=x86_64 .. && make"