CMake Tutorial2_1 创建并添加库到工程

一 内容
  1. 主要说明 创建库, 然后在工程中添加并使用它

  2. 文件目录

    step2_1
    |- MathFunctions
      |- CMakeLists.txt
      |- MathFunctions.h
      |- mysqrt.cc
    |- CMakeaLists.txt
    |- main.cc  
    
  3. 文件内容

  • MathFunctions/CMakeLists.txt

    add_library(MathFunctions mysqrt.cc)
    
  • MathFunctions/MathFunctions.h

    double mysqrt(double x);
    
  • MathFunctions/mysqrt.cc

    #include <iostream>
    
    // a hack square root calculation using simple operations
    double mysqrt(double x)
    {
      if (x <= 0) {
        return 0;
      }
    
      double result = x;
    
      // do ten iterations
      for (int i = 0; i < 10; ++i) {
        if (result <= 0) {
          result = 0.1;
        }
        double delta = x - (result * result);
        result = result + 0.5 * delta / result;
        std::cout << "Computing sqrt of " << x << " to be " << result << std::endl;
      }
      return result;
    }
    
    
  • CMakeLists.txt

    # 设置CMake最低版本
    cmake_minimum_required(VERSION 3.16)
    
    # 设置项目名称及版本
    project(Tutorial VERSION 1.0 LANGUAGES CXX)
    
    # 设置语言标准,此处为C++11
    set(CMAKE_CXX_STANDARD 11)
    set(CMAKE_CXX_STANDARD_REQUIRED True)
    
    # 生成库
    add_subdirectory(MathFunctions)
    
    # 生成可执行文件
    add_executable(Tutorial main.cc)
    
    # 链接库
    target_link_libraries(Tutorial PUBLIC MathFunctions)
    
    message("PROJECT_SOURCE_DIR=${PROJECT_SOURCE_DIR}")
    
    # 增加include路径到目标
    target_include_directories(Tutorial PUBLIC "${PROJECT_SOURCE_DIR}/MathFunctions/")
    
  • main.cc

    #include <iostream>
    
    #include "MathFunctions.h"
    
    int main() {
      
      std::cout << "mysqrt(1)=" << mysqrt(1) << std::endl;
      return 0;
    }
    
二 构建
  1. 与之前的Tutorial相同,创建并进入构建目录build
  2. 与之前的Tutorial相同, build&run
    lee@leedeMacBook-Pro build % cmake --build ..
    lee@leedeMacBook-Pro build % ./Tutorial 
    mysqrt(1)=Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    Computing sqrt of 1 to be 1
    1
    
三 Github
四 参考
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值