我通常使用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
Run Code Online (Sandbox Code Playgroud)
我做了这个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)
Run Code Online (Sandbox Code Playgroud)
我怎样才能拥有make run功能?或其他自定义功能?
Flo*_*ian 13
当它在CMake中进行测试时我更喜欢使用add_test().除了调用类似于make test运行测试的东西之外,它还可以通过ctest获得测试报告(与CMake 一起分发).
使用可执行文件的CMake目标的名称作为"命令" add_test()直接用excutable的路径替换它:
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)
Run Code Online (Sandbox Code Playgroud)
您可以进一步消除对shell的依赖,就像sh您要添加命令行参数以作为输入TextMiningApp传递test.txt一样:
add_test(
NAME TestTextMiningApp
COMMAND TextMiningApp -i "${CMAKE_SOURCE_DIR}/test.txt" "totoro.txt"
)
Run Code Online (Sandbox Code Playgroud)
并且无需添加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
Run Code Online (Sandbox Code Playgroud)
参考
添加具有给定名称的目标,该目标执行给定的命令。
用法很简单:
add_custom_target(run
COMMAND ./TextMiningCompiler <pathword> totoro.txt
COMMAND cat test.txt | time ./TextMiningApp totoro.txt
)
add_dependencies(run TextMiningCompiler TextMiningApp)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7679 次 |
| 最近记录: |