一 内容
-
主要说明 创建库, 然后在工程中添加并使用它。
-
文件目录
step2_1 |- MathFunctions |- CMakeLists.txt |- MathFunctions.h |- mysqrt.cc |- CMakeaLists.txt |- main.cc
-
文件内容
-
MathFunctions/CMakeLists.txt
add_library(MathFunctions mysqrt.cc)
-
MathFunctions/MathFunctions.h
double mysqrt(double x);
-
MathFunctions/mysqrt.cc
#include <iostream> // 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; }
-
CMakeLists.txt
# 设置CMake最低版本 cmake_minimum_required(VERSION 3.16) # 设置项目名称及版本 project(Tutorial VERSION 1.0 LANGUAGES CXX) # 设置语言标准,此处为C++11 set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED True) # 生成库 add_subdirectory(MathFunctions) # 生成可执行文件 add_executable(Tutorial main.cc) # 链接库 target_link_libraries(Tutorial PUBLIC MathFunctions) message("PROJECT_SOURCE_DIR=${PROJECT_SOURCE_DIR}") # 增加include路径到目标 target_include_directories(Tutorial PUBLIC "${PROJECT_SOURCE_DIR}/MathFunctions/")
-
main.cc
#include <iostream> #include "MathFunctions.h" int main() { std::cout << "mysqrt(1)=" << mysqrt(1) << std::endl; return 0; }
二 构建
- 与之前的Tutorial相同,创建并进入构建目录build
- 与之前的Tutorial相同, build&run
lee@leedeMacBook-Pro build % cmake --build .. lee@leedeMacBook-Pro build % ./Tutorial mysqrt(1)=Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 Computing sqrt of 1 to be 1 1
三 Github
- 代码已上传Github