ARM 项目中 x86 上的 CMake UnitTest

CMake UnitTest on x86 in ARM project

我 运行 一个 Cortex-M 项目 (ARM)。在这里,我想使用 CMake 功能 add_test 然后我可以继续调用 make test.

这很好用。

我遇到的问题是我添加的单元测试应该 运行 在我的 PC (x86) 上而不是在 ARM 上,因此测试失败。

我的子项目是:

project(dummy_math_lib_2)

add_library(${PROJECT_NAME}
        src/dummy_math_lib_2.cpp )
        
add_test(${PROJECT_NAME}
    src/dummy_math_lib_2.cpp
    unittest/src/unittest.cpp
)

target_include_directories(${PROJECT_NAME} PUBLIC inc)

target_link_libraries(${PROJECT_NAME})

在主 CMakeLists.txt 文件中,我启用“ENABLE_TESTING()”,然后执行以下操作:

cmake ..
make test

子项目树如下所示:

.
├── CMakeLists.txt
├── inc
│   └── dummy_math_lib_2.hpp
├── src
│   └── dummy_math_lib_2.cpp
└── unittest
    ├── inc
    └── src
        └── unittest.cpp

编辑:

project(dummy_math_lib_2)

add_library(${PROJECT_NAME}
        src/dummy_math_lib_2.cpp )
        
target_include_directories(${PROJECT_NAME} PUBLIC inc)

add_executable(UnitTest1 
    unittest/src/test.cpp
)

add_test(Test1 UnitTest1)

输出:

-- Configuring done
-- Generating done
-- Build files have been written to: /home/linux/workspace/cmake_t000D_cmake_DK/BUILD
Running tests...
Test project /home/linux/workspace/cmake_t000D_cmake_DK/BUILD
    Start 1: Test1
Could not find executable UnitTest1
Looked in the following places:
UnitTest1
UnitTest1
Release/UnitTest1
Release/UnitTest1
Debug/UnitTest1
Debug/UnitTest1
MinSizeRel/UnitTest1
MinSizeRel/UnitTest1
RelWithDebInfo/UnitTest1
RelWithDebInfo/UnitTest1
Deployment/UnitTest1
Deployment/UnitTest1
Development/UnitTest1
Development/UnitTest1
Unable to find executable: UnitTest1
1/1 Test #1: Test1 ............................***Not Run   0.00 sec

0% tests passed, 1 tests failed out of 1

Total Test time (real) =   0.00 sec

The following tests FAILED:
      1 - Test1 (Not Run)
Errors while running CTest
make: *** [Makefile:104: test] Error 8

EDIT2

好的,我发现了问题。解决方法如下:

cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug ..
make # <--- FIRST BUILD IT!
make test <--- THEN RUN THE TEST

这在理论上是 ;-) 现在我必须弄清楚如何为 x86 而不是 ARM 构建它。不过目前还好,谢谢大家帮助我。

add_test() 命令通常不应包含源文件。它应该使用任何必要的命令行参数简单地调用可执行文件。

你首先需要使用add_executable()来指定实际的单元测试可执行文件,你可以在add_test中引用这个目标:

add_library(${PROJECT_NAME}
    src/dummy_math_lib_2.cpp
)
        
target_include_directories(${PROJECT_NAME} PUBLIC inc)

# Define the test executable, UnitTest1.
add_executable(UnitTest1 
    unittest/src/unittest.cpp
)

# You may want to link the library under test to your test executable.
target_link_libraries(UnitTest1 PRIVATE ${PROJECT_NAME})

# Add the CTest unit test.
add_test(Test1 UnitTest1)

# Don't need this. As written, it does nothing.
<s>target_link_libraries(${PROJECT_NAME})</s>
</pre>

强烈建议您通读 add_test 文档,以了解此命令提供的更多详细信息和不同选项。