CMakeList.txtファイルに基づいてC ++ダイナミックライブラリとスタティックライブラリを作成します

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などのファイルが生成されます。静的ライブラリをコンパイルする必要がある場合は、それを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;
}

次のコマンドに従って上記の3つのファイルをコンパイルし、対応するファイルを生成します。

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!

おすすめ

転載: blog.csdn.net/linghu8812/article/details/108519580