"MathLibrary.cpp" - Build DLL Library

Q

How to build a C++ DLL library with Visual Studio command tools?

✍: FYIcenter.com

A

The next step to create a DLL library is to create library source code and build the library .dll file as shown in this tutorial:

1. Create the C++ source file, MathLibrary.cpp, with a text editor:

// MathLibrary.cpp : Defines the exported functions for the DLL application.  
// Compile by using: cl /EHsc /DMATHLIBRARY_EXPORTS /LD MathLibrary.cpp  

#include "MathLibrary.h"  

namespace MathLibrary  
{  
    double Functions::Add(double a, double b)  
    {  
        return a + b;  
    }  

    double Functions::Multiply(double a, double b)  
    {  
        return a * b;  
    }  

    double Functions::AddMultiply(double a, double b)  
    {  
        return a + (a * b);  
    }  
}

2. Compile MathLibrary.cpp into MathLibrary.dll with Visual Studio command "cl":

C:\fyicenter>cl /EHsc /DMATHLIBRARY_EXPORTS /LD MathLibrary.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.10.25019 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

MathLibrary.cpp
Microsoft (R) Incremental Linker Version 14.10.25019.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:MathLibrary.dll
/dll
/implib:MathLibrary.lib
MathLibrary.obj
   Creating library MathLibrary.lib and object MathLibrary.exp

C:\fyicenter>dir MathLibrary.*
10:56 AM               517 MathLibrary.cpp
10:58 AM            70,656 MathLibrary.dll
10:58 AM             1,133 MathLibrary.exp
10:57 AM               681 MathLibrary.h
10:58 AM             2,550 MathLibrary.lib
10:58 AM               892 MathLibrary.obj

3. Send 3 files to whoever wants to use your library:

  • Header file: MathLibrary.h - Needed to compile any C++ source code that uses your library.
  • Static Library file: MathLibrary.lib - Needed to build executables (.exe) that uses your library.
  • Dynamic Library file: MathLibrary.dll - Needed to run executables (.exe) that uses your library.

 

"MathClient.cpp" - Reference DLL Library

"MathLibrary.h" - Header File of DLL Library

Visual C++ Examples Provided by Microsoft

⇑⇑ Visual Studio Tutorials

2023-05-31, 2089🔥, 1💬