zoukankan      html  css  js  c++  java
  • CMake 自定义编译选项

    自定义编译选项

    CMake 允许为项目增加编译选项,从而可以根据用户的环境和需求选择最合适的编译方案

    例如,可以将 MathFunctions 库设为一个可选库,如果该选项为 ON ,就使用该库定义的数学函数来进行运算。否则就调用标准库中的数学函数库。

    修改 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})

    其中:

    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 库:

    #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 
    ", 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. 
    ");
        double result = power(base, exponent);
    #else
        printf("Now we use the standard library. 
    ");
        double result = pow(base, exponent);
    #endif
        printf("%g ^ %d is %g
    ", base, exponent, result);
        return 0;
    }
    编写 config.h.in 文件

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

    #cmakedefine USE_MYMATH

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

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

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

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

  • 相关阅读:
    javascript 文档标题滚动 实例
    Unity3D初学之2D动画制
    Uni2D 入门 -- Skeletal Animation
    Uni2D 入门 -- Asset Table
    Uni2D 入门 -- Atlas转载 http://blog.csdn.net/kakashi8841/article/details/17588095
    Uni2D 入门 -- Animation Clip 和 Animation API
    Uni2D入门
    将博客搬至CSDN
    unity 2048Game
    c#单例模式
  • 原文地址:https://www.cnblogs.com/dverdon/p/4573416.html
Copyright © 2011-2022 走看看