分享

CMake 简明教程(3)

 oskycar 2017-06-08
  原文网址: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中添加如下两行:

[python] view plain copy
  1. install (TARGETS MathFunctions DESTINATION bin)  
  2. install (FILES MathFunctions.h DESTINATION include)  

而对于这个项目,需要添加如下几行来告诉cmake如何install可执行文件及配置头文件:

[python] view plain copy
  1. # add the install targets  
  2. install (TARGETS Tutorial DESTINATION bin)  
  3. install (FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"          
  4.          DESTINATION include)  

这是install相关的所有内容了。这时你能够编译这个项目的代码,然后输入”make install”(或者在IDE编译INSTALL项目),之后相应的头文件,库,可执行文件都会被按规则install到需要的位置。cmake有一个变量CMAKE_INSTALL_PREFIX就是用来指定install目录的。



添加测试的过程也是很直接的。在顶层的CMakeLists.txt文件末尾添加一些基本的测试来确实项目是正常运行的。

[python] view plain copy
  1. # does the application run  
  2. add_test (TutorialRuns Tutorial 25)  
  3.    
  4. # does it sqrt of 25  
  5. add_test (TutorialComp25 Tutorial 25)  
  6.    
  7. set_tests_properties (TutorialComp25   
  8.   PROPERTIES PASS_REGULAR_EXPRESSION "25 is 5")  
  9.    
  10. # does it handle negative numbers  
  11. add_test (TutorialNegative Tutorial -25)  
  12. set_tests_properties (TutorialNegative  
  13.   PROPERTIES PASS_REGULAR_EXPRESSION "-25 is 0")  
  14.    
  15. # does it handle small numbers  
  16. add_test (TutorialSmall Tutorial 0.0001)  
  17. set_tests_properties (TutorialSmall  
  18.   PROPERTIES PASS_REGULAR_EXPRESSION "0.0001 is 0.01")  
  19.    
  20. # does the usage message work?  
  21. add_test (TutorialUsage Tutorial)  
  22. set_tests_properties (TutorialUsage  
  23.   PROPERTIES   
  24.   PASS_REGULAR_EXPRESSION "Usage:.*number")  

第一个测试用例只是简单地确定项目可正常运行,没有出现异常退出的情况,且最后返回一个0。这是一个CTest的基本形式。接下来的几个测试使用了PASS_REGULAR_EXPRESSION属性来检测输出结果为指定字符串。在这段代码示例中,正常情况下会输出字符串,输入数据有问题时倒输出使用说明。如果你想要添加很多测试的话,最好写一个函数,例如:

[python] view plain copy
  1. #define a macro to simplify adding tests, then use it  
  2. macro (do_test arg result)  
  3.   add_test (TutorialComp${arg} Tutorial ${arg})  
  4.   set_tests_properties (TutorialComp${arg}  
  5.     PROPERTIES PASS_REGULAR_EXPRESSION ${result})  
  6. endmacro (do_test)  
  7.    
  8. # do a bunch of result based tests  
  9. do_test (25 "25 is 5")  
  10. do_test (-25 "-25 is 0")  


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多