第二节

Step 2:adding a library

Exercise 1 - creating a library

1
2
3
4
5
6
7
8
9
10
add_library(MathFunctions MathFunctions.cxx mysqrt.cxx)

add_subdirectory(MathFunctions)

target_link_libraries(Tutorial PUBLIC MathFunctions)

target_include_directories(Tutorial PUBLIC
"${PROJECT_BINARY_DIR}"
"${PROJECT_SOURCE_DIR}/MathFunctions"
)

Exercise 2 - adding an option

1
2
3
4
5
6
7
8
9
10
11
12
# MathFunctions/CMakeLists.txt
option(USE_MYMATH "Use tutorialc provided math implementation" ON)

if(USE_MYMATH)
target_compile_definitions(MathFunctions PRIVATE "USE_MYmATH")
add_library(SqrtLibrary STATIC
mysqrt.cxx
)
target_link_libraries(MathFunctions PRIVATE SqrtLibrary)
endif()

add_library(MathFunction MathFunctions.cxx)
1
2
3
4
5
6
7
8
9
10
11
12
13
# MathFunctions/MathFunctions.cxx

#ifdef USE_MYMATH
return detail::mysqrt(x);
#else
return std::sqrt(x);
#endif

#ifdef USE_MYMATH
# include "mysqrt.h"
#endif

#include <cmath>