gpt4 book ai didi

makefile - CMake并添加测试程序命令

转载 作者:行者123 更新时间:2023-12-02 19:17:34 24 4
gpt4 key购买 nike

我通常使用 makefile 进行项目,但我想开始学习 CMake。我使用 makefile 不仅用于构建我的项目,还用于测试我的项目。这非常有用。我怎样才能用 CMake 做到这一点?

例如这个 makefile:

pathword=words.txt
flags=-std=c++11 -Wall -Wextra -g -Og
#flags=-std=c++11 -O3 -DNDEBUG -s

default: TextMiningCompiler TextMiningApp

TextMiningCompiler: TextMiningCompiler.cpp trie.cpp
g++ $(flags) TextMiningCompiler.cpp trie.cpp -o TextMiningCompiler

TextMiningApp: TextMiningApp.cpp
g++ $(flags) TextMiningApp.cpp -o TextMiningApp

run: TextMiningCompiler TextMiningApp
./TextMiningCompiler $(pathword) totoro.txt
cat test.txt | time ./TextMiningApp totoro.txt

clean:
trash TextMiningCompiler TextMiningApp

我制作了这个 CMakefile:

cmake_minimum_required(VERSION 2.8.9)
project (TextMining)
add_executable(TextMiningApp TextMiningApp.cpp)
add_executable(TextMiningCompiler TextMiningCompiler.cpp trie.cpp read_words_file.cpp)
set_property(TARGET TextMiningApp PROPERTY CXX_STANDARD 11)
set_property(TARGET TextMiningCompiler PROPERTY CXX_STANDARD 11)

怎样才能有make run功能?或者其他自定义函数?

最佳答案

当在 CMake 中进行测试时,我更喜欢使用 add_test() 。除了调用诸如 make test 之类的东西来运行测试之外,它还可以实现例如通过 获取测试报告(通过 CMake 分发)。

add_test() 中使用可执行文件的 CMake 目标名称作为“命令”,直接将其替换为可执行文件的路径:

cmake_minimum_required(VERSION 2.8.9)
project (TextMining)

enable_testing()

set(CMAKE_CXX_STANDARD 11)
set(pathword "${CMAKE_SOURCE_DIR}/words.txt")

add_executable(TextMiningCompiler TextMiningCompiler.cpp trie.cpp read_words_file.cpp)
add_test(
NAME TestTextMiningCompiler
COMMAND TextMiningCompiler "${pathword}" "totoro.txt"
)

add_executable(TextMiningApp TextMiningApp.cpp)
add_test(
NAME TestTextMiningApp
COMMAND sh -c "cat ${CMAKE_SOURCE_DIR}/test.txt | time $<TARGET_FILE:TextMiningApp> totoro.txt"
)
set_tests_properties(TestTextMiningApp PROPERTIES DEPENDS TestTextMiningCompiler)
<小时/>

如果您向 TextMiningApp 添加命令行参数以将 test.txt 传递为输入:

add_test(
NAME TestTextMiningApp
COMMAND TextMiningApp -i "${CMAKE_SOURCE_DIR}/test.txt" "totoro.txt"
)
<小时/>

并且无需添加 time 调用,因为通过 make test 执行测试时会自动测量总执行时间(顺便说一句,相当于调用 ctest ) :

$ make test
Running tests...
Test project [... path to project's binary dir ...]
Start 1: TestTextMiningCompiler
1/2 Test #1: TestTextMiningCompiler ........... Passed 0.11 sec
Start 2: TestTextMiningApp
2/2 Test #2: TestTextMiningApp ................ Passed 0.05 sec

100% tests passed, 0 tests failed out of 2

Total Test time (real) = 0.19 sec

引用

关于makefile - CMake并添加测试程序命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38436661/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com