本文中涉及到一个自定义库math_functions和一个主工程tutorial.cpp的组织。
如果定义了USE_MYMATH编译选项,就在编译时链接math_functions自定义库,如果没有定义这个选项,就不链接,使用系统给定的sqrt函数。
详细的文档如下,
Step 2: Adding a Library — CMake 3.23.0-rc1 Documentation
代码结构如下,
![](https://img.haomeiwen.com/i8982195/6a2b46c2bed362d6.png)
代码如下,
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
# 设置工程名称和版本
project(Tutorial VERSION 1.0)
# 指定C++标准
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED true)
# 是否使用自定义的 math实现
option(USE_MYMATH "Use tutorial provided math implementation" ON)
# 配置生成header文件
configure_file(tutorial_config.h.in tutorial_config.h)
# 添加 math_functions 库
if(USE_MYMATH)
add_subdirectory(math_functions)
list(APPEND EXTRA_LIBS math_functions)
list(APPEND EXTRA_INCLUDES "${PROJECT_SOURCE_DIR}/math_functions")
endif()
add_executable(Tutorial tutorial.cpp)
target_link_libraries(Tutorial PUBLIC ${EXTRA_LIBS})
target_include_directories(Tutorial PUBLIC "${PROJECT_BINARY_DIR}"
${EXTRA_INCLUDES})
tutorial_config.h.in
// Tutorial的配置选项和设置
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
#cmakedefine USE_MYMATH
tutorial.cpp
#include "tutorial_config.h"
#ifdef USE_MYMATH
#include "math_functions.h"
#endif
#include <cmath>
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
if(argc < 2) {
std::cout << argv[0] << " Version " << Tutorial_VERSION_MAJOR << "."
<< Tutorial_VERSION_MINOR << std::endl;
std::cout << "Usage: " << argv[0] << " number" << std::endl;
return EXIT_FAILURE;
}
double const input_val = std::stod(argv[1]);
#ifdef USE_MYMATH
double const ouput_val = mysqrt(input_val);
#else
double const ouput_val = sqrt(input_val);
#endif
std::cout << "The sqrt root of " << input_val << " is: " << ouput_val << std::endl;
return EXIT_SUCCESS;
}
math_functions/math_functions.h
#ifndef _FREDRIC_MATH_FUNCTIONS_H_
#define _FREDRIC_MATH_FUNCTIONS_H_
double mysqrt(double x);
#endif
math_functions/mysqrt.cpp
#include <iostream>
#include "math_functions.h"
// 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;
}
math_functions/CMakeLists.txt
add_library(math_functions mysqrt.cpp)
程序输出如下,
![](https://img.haomeiwen.com/i8982195/7f68b227ed9f482a.png)
网友评论