CMakeFiles.txt:
cmake_minimum_required(VERSION 3.0)
set the project name project(Tutorial)
add_executable(Tutorial tutorial.cpp)
tutorial.cpp:
#include \<cmath>
#include \<cstdlib>
#include \<iostream>
#include \<string>
int main(int argc, char* argv[]) {
if (argc < 2) {
std::cout << "Usage: " << argv[0] << " number" << std::endl;
return 1;
}
// convert input to double
const double inputValue = atof(argv[1]);
// calculate square root
const double outputValue = sqrt(inputValue);
std::cout << "The square root of " << inputValue
<< " is " << outputValue
<< std::endl;
return 0; }
执行:
mkdir build
cd build
cmake ../ #会自动寻找上一级目录里的cmake文件
cd ..
./Tutorial 5
output:
The square root of 5 is 2.23607
文件解构:
首先建一个文件夹MathFunctions。在/MathFunction 文件夹中创建一个文件mysqrt.cpp:
#include <iostream>
?
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;
}
并且创建头文件MathFunctions.h:
double mysqrt(double x);
在库文件下也要新建cmakefile.txt:
add_library() 为创建静态或动态库,库名称自定(如Message), 静态库或动态库由两个关键字指定(STATIC、SHARED)。再添加生成库的源文件路径
add_library(MathFunctions mysqrt.cpp)
执行:
cd build
cmake ../
cmake --build .
参考:https://blog.csdn.net/m0_46327721/article/details/128517261