文章目录
基于CMakeList.txt文件创建C++动态库及静态库
1. CMakeList.txt文件
cmake_minimum_required(VERSION 3.12)
project(calculate)
set(CMAKE_CXX_STANDARD 14)
add_library(myfunctions SHARED MyMathFuncs.cpp)
add_executable(calculate main.cpp)
target_link_libraries(calculate myfunctions)
以上是编译动态库的CMakeList.txt文件,编译后会生成dll或者so文件。如需编译静态库,将add_library(myfunctions SHARED MyMathFuncs.cpp)
改为add_library(myfunctions STATIC MyMathFuncs.cpp)
即可,编译后会生成.lib或.a文件。
2. C++文件
2.1 MyMathFuncs.h
#ifndef MYMATHFUNCS_H
#define MYMATHFUNCS_H
class MyMathFuncs
{
public:
MyMathFuncs();
~MyMathFuncs();
// Returns a + b
static double Add(double a, double b);
// Returns a - b
static double Subtract(double a, double b);
// Returns a * b
static double Multiply(double a, double b);
// Returns a / b
// Throws const std::invalid_argument& if b is 0
static double Divide(double a, double b);
};
#endif //MYMATHFUNCS_H
2.2 MyMathFuncs.cpp
#include "MyMathFuncs.h"
#include <stdexcept>
MyMathFuncs::MyMathFuncs()
= default;
MyMathFuncs::~MyMathFuncs()
= default;
double MyMathFuncs::Add(double a, double b)
{
return a + b;
}
double MyMathFuncs::Subtract(double a, double b)
{
return a - b;
}
double MyMathFuncs::Multiply(double a, double b)
{
return a * b;
}
double MyMathFuncs::Divide(double a, double b)
{
if (b == 0)
{
throw std::invalid_argument("b cannot be zero!");
}
return a / b;
}
2.3 main.cpp
#include <iostream>
#include "MyMathFuncs.h"
int main() {
double a = 7.4;
int b = 99;
std::cout << "a + b = " << MyMathFuncs::Add(a, b) << std::endl;
std::cout << "a - b = " << MyMathFuncs::Subtract(a, b) << std::endl;
std::cout << "a * b = " << MyMathFuncs::Multiply(a, b) << std::endl;
std::cout << "a / b = " << MyMathFuncs::Divide(a, b) << std::endl;
try
{
std::cout << "a / 0 = " << MyMathFuncs::Divide(a, 0) << std::endl;
}
catch (const std::invalid_argument &e)
{
std::cout << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
将以上三个文件按以下命令进行编译可以生成相应文件:
mkdir build && cd build
cmake ..
make -j
3.运行
在命令行输入./calculate
会得到如下结果:
a + b = 106.4
a - b = -91.6
a * b = 732.6
a / b = 0.0747475
a / 0 = Caught exception: b cannot be zero!