Create C++ dynamic library and static library based on CMakeList.txt file

Create C++ dynamic library and static library based on CMakeList.txt file

1. CMakeList.txt file

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)

The above is the CMakeList.txt file for compiling the dynamic library. After compiling, the dll or so file will be generated. If you need to compile a static library, just add_library(myfunctions SHARED MyMathFuncs.cpp)change it add_library(myfunctions STATIC MyMathFuncs.cpp), and a .lib or .a file will be generated after compilation.

2. C++ files

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;
}

Compile the above three files according to the following command to generate the corresponding files:

mkdir build && cd build
cmake ..
make -j

3. Run

Enter the ./calculatefollowing result on the command line :

a + b = 106.4
a - b = -91.6
a * b = 732.6
a / b = 0.0747475
a / 0 = Caught exception: b cannot be zero!

Guess you like

Origin blog.csdn.net/linghu8812/article/details/108519580