您的位置:首页 > 财经 > 产业 > Cmake教程之二(添加一个库)

Cmake教程之二(添加一个库)

2024/10/6 8:35:01 来源:https://blog.csdn.net/qq_51691526/article/details/141729405  浏览:    关键词:Cmake教程之二(添加一个库)

CMake 教程 - 二、添加库

介绍

在第一步中,在项目中创建并使用一个库;同时,使库的使用变得可选

练习 1: 创建一个库

目标

理解cmake中添加和使用一个库的过程

步骤

  1. MathFunctions 目录中的 CMakeLists.txt 中创建库
    # 添加一个库,后面的参数是库的源文件(.c,.cpp,.cxx)
    # 默认静态库
    add_library(MathFunctions MathFunctions.cxx mysqrt.cxx)
    
  2. 在顶层 CMakeLists.txt 文件中添加 add_subdirectory 调用
    # 这一行的作用是告诉 CMake 在构建过程中需要进入 MathFunctions 子目录,
    # 并处理该目录中的 CMakeLists.txt 文件。
    # 这个目录中的 CMakeLists.txt 文件定义了 MathFunctions 库的具体内容。
    # 通过这个命令,CMake 会在链接 Tutorial 可执行文件前先根据MathFunctions目录中CMakeLists.txt构建出MathFunctions库
    add_subdirectory(MathFunctions)
    
  3. 先确定 Tutorial 可执行文件的名称,然后列出需要链接的库和头文件目录
    add_executable(Tutorial tutorial.cxx) 
    
  4. 将 MathFunctions 库链接到 Tutorial 可执行文件上
    target_link_libraries(Tutorial PUBLIC MathFunctions)
    
  5. tutorial.cxx 中包含 MathFunctions.h
    # 将 PROJECT_BINARY_DIR 和 PROJECT_SOURCE_DIR 添加到 include 目录中
    # 这样 Tutorial 可执行文件就可以找到 MathFunctions.h 文件了。
    target_include_directories(Tutorial PUBLIC"${PROJECT_BINARY_DIR}""${PROJECT_SOURCE_DIR}/MathFunctions"  )
    
  6. 使用自定义库函数mysqrt
    #include "MathFunctions.h"
    #include <cstdio>
    #include <cstdlib>
    int main(int argc, char *argv[])
    {if (argc < 2){fprintf(stdout, "Usage: %s number\n", argv[0]);return 1;}float inputValue = atof(argv[1]);//使用的是库里面命名空间中的函数float outputValue = MathFunctions::sqrt(inputValue);fprintf(stdout, "The square root of %g is %g\n", inputValue, outputValue);return 0;
    }
    

构建和运行

  • 创建构建目录并配置项目:
    mkdir Step2_build
    cd Step2_build
    cmake ../Step2
    cmake --build .
    
  • 运行可执行文件并验证结果:
    ./Tutorial 25
    

练习 2: 添加一个选项

目标

MathFunctions 库添加一个选项,以允许开发者选择使用自定义的平方根实现或标准实现。

步骤

  1. MathFunctions/CMakeLists.txt 中使用 option 命令创建变量 USE_MYMATH
    option(USE_MYMATH "Use custom square root implementation" ON)
    
  2. 基于 USE_MYMATH 选项在 MathFunctions.cxx 中选择平方根实现
    #ifdef USE_MYMATH
    #include "mysqrt.h"
    #endifdouble mathfunctions::sqrt(double x) {#ifdef USE_MYMATHreturn mysqrt(x);#elsereturn std::sqrt(x);#endif
    }
    
  3. MathFunctions/CMakeLists.txt 中创建并链接 SqrtLibrary
    if (USE_MYMATH)add_library(SqrtLibrary mysqrt.cxx)target_link_libraries(MathFunctions PRIVATE SqrtLibrary)target_compile_definitions(MathFunctions PRIVATE "USE_MYMATH")
    endif()
    

构建和运行

  • 使用现有的构建目录重新构建项目:
    cd ../Step2_build
    cmake --build .
    
  • 运行可执行文件并验证结果:
    ./Tutorial 25
    
  • 切换 USE_MYMATH 选项为 OFF 并重新构建:
    cmake ../Step2 -DUSE_MYMATH=OFF
    cmake --build .
    
  • 再次运行可执行文件,确保程序在 USE_MYMATH 关闭时仍然正常运行。

这样,便可以通过切换 USE_MYMATH 的值来决定是否使用自定义的平方根函数 mysqrt

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com