CMake Tutorial Step2

原文链接: Step 2: Adding a Library

1. 在次级目录里构建自定义库

    1. Cmakelist 只需要一句话
      add_library(MathFunctions mysqrt.cxx)

2. 在顶层目录中添加次级文件夹

    1. CMakeList 中添加
      # add the MathFunctions library
      add_subdirectory(MathFunctions)
      
      # add the executable
      add_executable(Tutorial tutorial.cxx)
      
      target_link_libraries(Tutorial PUBLIC MathFunctions)
      
      # add the binary tree to the search path for include files
      # so that we will find TutorialConfig.h
      target_include_directories(Tutorial PUBLIC
                                "${PROJECT_BINARY_DIR}"
                                "${PROJECT_SOURCE_DIR}/MathFunctions"
                                )
      
      这通过 add_subdirectory 直接把次级文件夹中内容在当前目录里构建了
      所以可以直接使用次级文件夹构建出的库 MathFunctions
    1. 把次级文件夹设置为可选项
      option(USE_MYMATH "Use tutorial provided math implementation" ON)
      # configure a header file to pass some of the CMake settings
      # to the source code
      configure_file(TutorialConfig.h.in TutorialConfig.h)
      
      通过添加宏来控制,默认是 ON ,可以在编译选项里修改
      if(USE_MYMATH)
        add_subdirectory(MathFunctions)
        list(APPEND EXTRA_LIBS MathFunctions)
        list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/MathFunctions")
      endif()
      # add the executable
      add_executable(Tutorial tutorial.cxx)
      target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})
      # add the binary tree to the search path for include files
      # so that we will find TutorialConfig.h
      target_include_directories(Tutorial PUBLIC
                                 "${PROJECT_BINARY_DIR}"
                                 ${EXTRA_INCLUDES}
                                 )
      
    1. 把 USE_MYMATH 传入到 cpp 里
      在 TutorialConfig.h.in 中添加
      #cmakedefine USE_MYMATH
      这样生成的 .h 里会多一个宏
      // the configured options and settings for Tutorial
      #define Tutorial_VERSION_MAJOR 1
      #define Tutorial_VERSION_MINOR 0
      #define USE_MYMATH
      
    1. 取消 USE_MYMATH
      直接编译选项里设置
      cmake ../Step2 -DUSE_MYMATH=OFF
      这会让 CMakeList 里的 USE_MYMATH 变为 OFF
      并且 .h 中的相关 define 直接被注释掉
      // the configured options and settings for Tutorial
      #define Tutorial_VERSION_MAJOR 1
      #define Tutorial_VERSION_MINOR 0
      /* #undef USE_MYMATH */
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值