Cmake:指定一个单独的构建工具链进行测试?

dan*_*hep 5 unit-testing cmake

我正在使用 CMake 构建嵌入式系统的项目,但我的单元测试是在 x86 主机上完成的。因此,我需要使用一种完全不同的编译器来构建用于交叉编译二进制文件的测试。

我的项目顶层有一个主 CMakeLists.txt 文件,然后在我的测试文件夹中添加了另一个文件add_subdirectory到顶层。我应该将它们完全分开还是有更好的方法来实现这一点?

在没有交叉编译器的情况下运行我的主构建将导致它失败,因此它确实需要是一个单独的测试过程。

Kam*_*Cuk 0

我应该把它们完全分开吗

没必要。保持目标之间适当的最小依赖关系,添加EXCLUDE_FROM_ALL到测试目标并通过良好的分组管理目标。或者仅显式编译您想要编译的目标。

或者有更好的方法来实现这一点吗?

已知的限制:

  • 每个 cmake 配置可能有一个编译器。
  • 您不能(轻松地;)在编译器之间“切换”并针对不同的目标使用不同的编译器。
  • 要使用不同的编译器,您必须重新配置 cmake。

解决方案:

  • 为单元测试和正常编译配置不同的 cmake。
  • 通常使用外部工具/脚本/任何东西来管理 cmake 配置并执行您想要的操作。
  • 通过正确标记单元测试并EXCLUDE_FROM_ALL在未使用的目标上使用,仅编译您想要的内容。

我通常使用 a Makefile,只是因为 shell 会自动检测自动完成功能:

all: normal_build
normal_build:
     cmake -S . -B _build/$@ \
            -DCMAKE_TOOLCHAIN_FILE=the_target_toolchain_file.camle
     cmake --build _build/$@ --target the_firmware

unit_tests_on_pc:
     camke -S . -B _build/$@ \
            -DCMAKE_C_FLAGS="-fsanitize -Wall -Wextra -pedantic etc...."
     cmake --build _build/$@ --target unit_tests # note - compile only unit tests
     cd _build/$@ && ctest -LE "on_target"

# tests with set CMAKE_CROSSCOMPILING_EMULATOR in toolchain file
unit_tests_on_simulator:
     cmake -S . -B _build/$@ \
           -DCMAKE_TOOLCHAIN_FILE=the_toolchain_file_for_simulator.camke
     cmake --build _build/$@ --target unit_tests
     cd _build/$@ && ctest -E "on_target"

# tests with set CMAKE_CROSSCOMPILING_EMULATOR to a script
# that flashes some connected target with the firmware and get's output from it
unit_tests_on_target:
     cmake -S . -B _build/$@ \
           -DCMAKE_TOOLCHAIN_FILE=the_toolchain_file_for_unit_tests.camke
     # special targets compiled here - only integration tests for real hardware!
     cmake --build _build/$@ --target integration_tests
     cd _build/$@ && ctest -E "on_target"

# etc..
Run Code Online (Sandbox Code Playgroud)