CMake 自定义编译选项

自定义编译选项

CMake 容许为项目增长编译选项,从而能够根据用户的环境和需求选择最合适的编译方案html

例如,能够将 MathFunctions 库设为一个可选库,若是该选项为 ON ,就使用该库定义的数学函数来进行运算。不然就调用标准库中的数学函数库。ide

修改 CMakeLists 文件

咱们要作的第一步是在顶层的 CMakeLists.txt 文件中添加该选项:函数

# CMake 最低版本号要求
cmake_minimum_required (VERSION 2.8)
# 项目信息
project (Demo4)
# 加入一个配置头文件,用于处理 CMake 对源码的设置
configure_file (
  "${PROJECT_SOURCE_DIR}/config.h.in"
  "${PROJECT_BINARY_DIR}/config.h"
  )
# 是否使用本身的 MathFunctions 库
option (USE_MYMATH
       "Use provided math implementation" ON)
# 是否加入 MathFunctions 库
if (USE_MYMATH)
  include_directories ("${PROJECT_SOURCE_DIR}/math")
  add_subdirectory (math)  
  set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
# 查找当前目录下的全部源文件
# 并将名称保存到 DIR_SRCS 变量
aux_source_directory(. DIR_SRCS)
# 指定生成目标
add_executable(Demo ${DIR_SRCS})
# 添加连接库
target_link_libraries (Demo  ${EXTRA_LIBS})

 

其中:ui

  1. configure_file 命令用于加入一个配置头文件 config.h ,这个文件由 CMake 从 config.h.in 生成,经过这样的机制,将能够经过预约义一些参数和变量来控制代码的生成。
  2. option 命令添加了一个 USE_MYMATH 选项,而且默认值为 ON
  3. USE_MYMATH 变量的值决定是否使用咱们本身编写的 MathFunctions 库。

 

修改 main.cc 文件

以后修改 main.cc 文件,让其根据 USE_MYMATH 的预约义值来决定是否调用标准库仍是 MathFunctions 库:spa

#include 
#include 
#include 
"config.h"
#ifdef USE_MYMATH
  #include "math/MathFunctions.h"
#else
  #include 
#endif
int main(int argc, char *argv[])
{
    if (argc < 3){
        printf("Usage: %s base exponent \n", argv[0]);
        return 1;
    }
    double base = atof(argv[1]);// Convert string to float
    int exponent = atoi(argv[2]); // Convert string to integer
    
#ifdef USE_MYMATH
    printf("Now we use our own Math library. \n");
    double result = power(base, exponent);
#else
    printf("Now we use the standard library. \n");
    double result = pow(base, exponent);
#endif
    printf("%g ^ %d is %g\n", base, exponent, result);
    return 0;
}

 

编写 config.h.in 文件

上面的程序值得注意的是,这里引用了一个 config.h 文件,这个文件预约义了 USE_MYMATH 的值。但咱们并不直接编写这个文件,为了方便从 CMakeLists.txt 中导入配置,咱们编写一个 config.h.in 文件,内容以下:code

#cmakedefine USE_MYMATH

这样 CMake 会自动根据 CMakeLists 配置文件中的设置自动生成 config.h 文件。htm

参考文档http://www.cmake.org/cmake-tutorial/blog

这里有更加完整的中文版,感谢大神!!:文档

http://www.cnblogs.com/coderfenghc/archive/2013/01/20/2846621.html#3176055get

相关文章
相关标签/搜索