# cmake使用教程（二）-添加库

2018-01-30 10:42:50来源:https://juejin.im/post/5a6f3cda6fb9a01c9d32231c作者:稀土掘金人点击

)。

，它只有一个名为mysqrt

double mysqrt(double x);

#include "MathFunctions.h"
#include <stdio.h>
// a hack square root calculation using simple operations
double mysqrt(double x)
{
if (x <= 0) {
return 0;
}
double result;
double delta;
result = x;
// do ten iterations
int i;
for (i = 0; i < 10; ++i) {
if (result <= 0) {
result = 0.1;
}
delta = x - (result * result);
result = result + 0.5 * delta / result;
fprintf(stdout, "Computing sqrt of %g to be %g/n", x, result);
}
return result;
}

include_directories ("\${PROJECT_SOURCE_DIR}/MathFunctions")

.
├── CMakeLists.txt
├── MathFunctions
│ ├── CMakeLists.txt
│ ├── MathFunctions.h
│ └── mysqrt.cxx
├── TutorialConfig.h.in
└── tutorial.cxx

MathFunctions

# should we use our own math functions?
option (USE_MYMATH
"Use tutorial provided math implementation" ON)

#
if (USE_MYMATH)
include_directories ("\${PROJECT_SOURCE_DIR}/MathFunctions")
set (EXTRA_LIBS \${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)

#cmakedefine USE_MYMATH

// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"
#ifdef USE_MYMATH
#include "MathFunctions.h"
#endif

int main (int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stdout,"%s Version %d.%d/n", argv[0],
Tutorial_VERSION_MAJOR,
Tutorial_VERSION_MINOR);
fprintf(stdout,"Usage: %s number/n",argv[0]);
return 1;
}

double inputValue = atof(argv[1]);

#ifdef USE_MYMATH
double outputValue = mysqrt(inputValue);
#else
double outputValue = sqrt(inputValue);
#endif

fprintf(stdout,"The square root of %g is %g/n",
inputValue, outputValue);
return 0;
}

 ~/Desktop/Tutorial/Step2/ ./Tutorial 4
Computing sqrt of 4 to be 2.5
Computing sqrt of 4 to be 2.05
Computing sqrt of 4 to be 2.00061
Computing sqrt of 4 to be 2
Computing sqrt of 4 to be 2
Computing sqrt of 4 to be 2
Computing sqrt of 4 to be 2
Computing sqrt of 4 to be 2
Computing sqrt of 4 to be 2
Computing sqrt of 4 to be 2
The square root of 4 is 2

 ~/Desktop/Tutorial/Step2/ ./Tutorial 4
The square root of 4 is 2