CMAKE_step2:添加一个库

9 篇文章 0 订阅

将上篇文章中的函数,放到一个库中,再由主程序调用。目录结构上做了一点调整,增加了一个库的目录MathFunctions,具体如下,

MathFunctions目录中包含3个文件:CMakeLists.txt,函数声明头文件MathFunction,函数体实现源文件mysqrt.cxx

  • 库函数目录中的CMakeLists.txt内容

很简单,只有一行,具体如下,

add_library(MathFunctions mysqrt.cxx)

  • MathFunctions.h内容

#ifndef  MATHFUNC_H
#define MATHFUNC_H

double mysqrt(double n);

#endif

  • mysqrt.cxx内容

#include <math.h>
#include "MathFunctions.h"

double mysqrt(double dpara)
{
    double res = sqrt(dpara);
    return res;
}

上面是新加内容的显示,下面将更新的主目录step2的各文件内容显示如下:

  • CMakeLists.txt

cmake_minimum_required(VERSION 3.10)

#set the project name and version
project(Tutorial VERSION 1.0)

#specify the C++ standard
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)

option(USE_MYMATH "Use tutorial provided math implementation" ON)

configure_file(TutorialConfig.h.in TutorialConfig.h)

if(USE_MYMATH)
    #add the MathFunctions Library
    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}) 

target_include_directories(Tutorial PUBLIC
                           "${PROJECT_BINARY_DIR}"
               "${EXTRA_INCLUDES}"
                           )

  • tutorial.cxx

#include <iostream>
#include <string>
#include "TutorialConfig.h"

#ifdef USE_MYMATH
#include "MathFunctions.h"
#endif

using namespace std;

int main(int argc, char** argv) {
  if (argc < 2) {
    // report version
    std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
              << Tutorial_VERSION_MINOR << std::endl;
    std::cout << "Usage: " << argv[0] << " number" << std::endl;
    return 1;
  }

    const double inputValue = std::stod(argv[1]);

#ifdef USE_MYMATH
    const double outputValue = mysqrt(inputValue );
    cout << "use self defined sqrt lib\n";
#else
    const double outputValue = sqrt(inputValue);
    cout << "use system math lib\n";
#endif
    cout << outputValue << endl;

    return 1;
}

  • TutorialConfig.h.in

#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@

#cmakedefine USE_MYMATH

编译与执行:

  1. 使能USE_MYMATH选项

1)cmake .. -DUSE_MYMATH=ON

 

2)cmake  --build .

 

3) Debug\Tutorial.exe 64

 

     2. Disable外部库USE_MYMATH选项

1)cmake .. -DUSE_MYMATH=OFF

2)cmake  --build .

 

 3) Debug\Tutorial.exe 64

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值