将上篇文章中的函数,放到一个库中,再由主程序调用。目录结构上做了一点调整,增加了一个库的目录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
编译与执行:
- 使能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