如何在CMakeLists.txt中检测到我是否正在交叉编译?

时间:2016-11-10 12:59:07

标签: cmake

CMake文档建议在交叉编译时设置CMAKE_CROSSCOMPILING。在我的CMakeLists.txt中,我有以下几行:

IF(CMAKE_CROSSCOMPILING)
    message(STATUS "Cross-compiling so skipping unit tests.")
    option(GAME_PORTAL_UNIT_TEST "Enable unit testing of Game Portal code" OFF)
ELSE()
    message(STATUS "Enabling unit testing of Game Portal code")
    option(GAME_PORTAL_UNIT_TEST "Enable unit testing of Game Portal code" ON)
ENDIF()

跑步的输出:

cmake -DCMAKE_TOOLCHAIN_FILE=../crosscompile/raspberry_pi/CMakeCross.txt .

包含文本“启用游戏门户代码的单元测试”,所以很明显这个变量没有被设置,所以无论如何它都会被评估为真。

我尝试修改CMakeCross.txt以包含:

set(CMAKE_CROSSCOMPILING ON CACHE BOOL "Cross-compiling" FORCE)

在清理旧的CMakeCache.txt并重新运行我的cmake命令后,我可以看到新的CMakeCache.txt现在包含了这个变量,但是我仍然得到了与之前关于启用的单元测试相同的结果。

如何可靠地检测到我正在交叉编译,以便我可以正确禁用单元测试?

根据要求,完整的交叉编译文件是:

# Set minimum cmake version required for cross-compiling to work.
cmake_minimum_required(VERSION 2.6)
# Build with rm CMakeCache.txt; cmake -DCMAKE_TOOLCHAIN_FILE=/home/crosscompile/dev/raspberry_pi/CMakeCross.txt .. 

# Set target system name.
SET (CMAKE_SYSTEM_NAME Linux)

# Set compiler name.
SET (CMAKE_C_COMPILER arm-linux-gnueabihf-gcc)
SET (CMAKE_CXX_COMPILER arm-linux-gnueabihf-g++)

# Set path(s) to search for libraries/binaries/headers.
SET (CMAKE_FIND_ROOT_PATH /home/crosscompile/dev/raspberry_pi/rootfs/)

# Ensure only cross-compiler directories are searched.
SET (ONLY_CMAKE_FIND_ROOT_PATH TRUE)

# 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)

# Set output/install directory to safe place.
SET (CMAKE_INSTALL_PREFIX /home/crosscompile/dev/raspberry_pi/install/)

set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -rpath-link=/lib/arm-linux-gnueabihf")
set(THREADS_PTHREAD_ARG 0)
set(CMAKE_CROSSCOMPILING ON CACHE BOOL "Cross-compiling" FORCE)

3 个答案:

答案 0 :(得分:2)

CMAKE_CROSSCOMPILING的测试必须在CMakeLists.txt中的“project”指令之后。

答案 1 :(得分:1)

使用源内版本,在更改配置参数时,需要手动清理构建文件

例如,如果您之前执行了 native 构建,然后决定交叉编译,则需要执行手动清理:CMake无法自动将构建目录从一种构建类型调整到另一种构建类型。

这是不建议使用源内构建的原因之一,应该用源外构建替换。

答案 2 :(得分:0)

这在我的例子中起作用:

  • 的CMakeLists.txt
    cmake_minimum_required(VERSION 3.0)
    project(STM32F4Examples C)    

    set(CMAKE_CROSSCOMPILE OFF CACHE BOOL "is crosscompiled")
    message(STATUS "CMAKE_CROSSCOMPILE ${CMAKE_CROSSCOMPILE}")
  • CMakeToolChain_STM32F4.txt
    # cmake toolchain
    # Use this file with cmake -DCMAKE_TOOLCHAIN_FILE=[PATH/TO/This/FILE] PATH/TO/SOURCES

    set(CMAKE_CROSSCOMPILE ON CACHE BOOL "is crosscompiled" FORCE)