原文网址:http:///cmake/help/cmake_tutorial.html
教程中所有的代码都可以在这里找到:http://public./cgi-bin/viewcvs.cgi/CMake/Tests/Tutorial/
这一节中,我们会为项目添加安装和测试规则。安装规则(install rule)可直接添加,对于Linux和mac用记来讲,install太常用了,因为类Unix系统的库支持方面做得确实比windows好。windows用户可能不大熟悉,其实也简单,就是把编译好的文件进行一些处理(比如mac上需要使用otool修改库文件使用的支持库的路径,默认都是绝对路径)后复制到用户指定的位置。要安装MathFunctions库,需要在MathFunctions的CMakeLists.txt中添加如下两行:
- install (TARGETS MathFunctions DESTINATION bin)
- install (FILES MathFunctions.h DESTINATION include)
而对于这个项目,需要添加如下几行来告诉cmake如何install可执行文件及配置头文件:
- # add the install targets
- install (TARGETS Tutorial DESTINATION bin)
- install (FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"
- DESTINATION include)
这是install相关的所有内容了。这时你能够编译这个项目的代码,然后输入”make install”(或者在IDE编译INSTALL项目),之后相应的头文件,库,可执行文件都会被按规则install到需要的位置。cmake有一个变量CMAKE_INSTALL_PREFIX就是用来指定install目录的。
添加测试的过程也是很直接的。在顶层的CMakeLists.txt文件末尾添加一些基本的测试来确实项目是正常运行的。
- # does the application run
- add_test (TutorialRuns Tutorial 25)
-
- # does it sqrt of 25
- add_test (TutorialComp25 Tutorial 25)
-
- set_tests_properties (TutorialComp25
- PROPERTIES PASS_REGULAR_EXPRESSION "25 is 5")
-
- # does it handle negative numbers
- add_test (TutorialNegative Tutorial -25)
- set_tests_properties (TutorialNegative
- PROPERTIES PASS_REGULAR_EXPRESSION "-25 is 0")
-
- # does it handle small numbers
- add_test (TutorialSmall Tutorial 0.0001)
- set_tests_properties (TutorialSmall
- PROPERTIES PASS_REGULAR_EXPRESSION "0.0001 is 0.01")
-
- # does the usage message work?
- add_test (TutorialUsage Tutorial)
- set_tests_properties (TutorialUsage
- PROPERTIES
- PASS_REGULAR_EXPRESSION "Usage:.*number")
第一个测试用例只是简单地确定项目可正常运行,没有出现异常退出的情况,且最后返回一个0。这是一个CTest的基本形式。接下来的几个测试使用了PASS_REGULAR_EXPRESSION属性来检测输出结果为指定字符串。在这段代码示例中,正常情况下会输出字符串,输入数据有问题时倒输出使用说明。如果你想要添加很多测试的话,最好写一个函数,例如:
- #define a macro to simplify adding tests, then use it
- macro (do_test arg result)
- add_test (TutorialComp${arg} Tutorial ${arg})
- set_tests_properties (TutorialComp${arg}
- PROPERTIES PASS_REGULAR_EXPRESSION ${result})
- endmacro (do_test)
-
- # do a bunch of result based tests
- do_test (25 "25 is 5")
- do_test (-25 "-25 is 0")
|