在【CMAKE】【Tutorial】03 指定C++标准的程序基础上进行修改。
1. 添加文件夹与文件
在CMake_Tutorial 文件夹中添加子目录MathFunctions ,并在该目录中添加以下三个文件:
- CMakeLists.txt
- MathFunctions.h
- mysqrt.cpp
文件内容分别如下:
1.1 CMakeLists.txt
add_library(MathFunctions mysqrt.cpp)
1.2 MathFunctions.h
double mysqrt(double x);
1.3 mysqrt.cpp
#include <iostream>
#include "MathFunctions.h"
double mysqrt(double x)
{
if (x <= 0)
{
return 0;
}
double result = x;
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;
}
2. 修改顶层目录中的CMakeLists.txt
cmake_minimum_required(VERSION 3.20 FATAL_ERROR)
project(Tutorials)
# 指定C++版本
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# 设置版本号
set(Tutorial_VERSION_MAJOR 1)
set(Tutorial_VERSION_MINOR 0)
# 添加配置文件,编译后 TutorialConfig.h.in 将被转化成 TutorialConfig.h 文件,该文件位于项目文件的根目录
configure_file(TutorialConfig.h.in TutorialConfig.h)
# 添加一个名称为 MathFunctions 的库
add_subdirectory(MathFunctions)
add_executable(Tutorial main.cpp)
# 包含特定的头文件查找目录,以便于找到TutorialConfig.h文件
target_include_directories(Tutorial PUBLIC
${PROJECT_BINARY_DIR}
${PROJECT_SOURCE_DIR}/MathFunctions)
# 添加链接库文件
target_link_libraries(Tutorial PUBLIC MathFunctions)
3. 修改main.cpp文件
#include <iostream>
#include "TutorialConfig.h"
#include "MathFunctions.h"
int main(int argc, char** argv)
{
std::cout << "Hello World!" << std::endl;
std::cout << " Version: " << Tutorial_VERSION_MAJOR << "." << Tutorial_VERSION_MINOR << std::endl;
std::cout << "C++ 11: " << std::atof("100") << std::endl;
std::cout << "MathFunctions: " << mysqrt(192.1) << std::endl;
return EXIT_SUCCESS;
}
|