16 out of 26 rated this helpful - Rate this topic

Walkthrough: Creating and Using a Dynamic Link Library (C++)

The first type of library we will create is a dynamic link library (DLL). Using DLLs is a great way to reuse code. Rather than re-implementing the same routines in every program that you create, you write them one time and reference them from applications that need the functionality.

This walkthrough covers the following:

  • Creating a new dynamic link library (DLL) project.

  • Adding a class to the dynamic link library.

  • Creating an application that references the dynamic link library.

  • Using the functionality from the class library in the console application.

  • Running the application.

This topic assumes that you understand the fundamentals of the C++ language.

To create a new dynamic link library (DLL) project

  1. From the File menu, select New and then Project….

  2. On the Project types pane, under Visual C++, select Win32.

  3. On the Templates pane, select Win32 Console Application.

  4. Choose a name for the project, such as MathFuncsDll, and type it in the Name field. Choose a name for the solution, such as DynamicLibrary, and type it in the Solution Name field.

  5. Click OK to start the Win32 application wizard. On the Overview page of the Win32 Application Wizard dialog box, click Next.

  6. On the Application Settings page of the Win32 Application Wizard, under Application type, select DLL if it is available or Console application if DLL is not available. Some versions of Visual Studio do not support creating a DLL project by using wizards. You can change this later to make your project compile into a DLL.

  7. On the Application Settings page of the Win32 Application Wizard, under Additional options, select Empty project.

  8. Click Finish to create the project.

To add a class to the dynamic link library

  1. To create a header file for a new class, from the Project menu, select Add New Item…. The Add New Item dialog box will be displayed. On the Categories pane, under Visual C++, select Code. On the Templates pane, select Header File (.h). Choose a name for the header file, such as MathFuncsDll.h, and click Add. A blank file will be displayed.

  2. Add a simple class named MyMathFuncs to do common mathematical operations, such as addition, subtraction, multiplication, and division. The code should resemble the following:

    // MathFuncsDll.h
    
    namespace MathFuncs
    {
        class MyMathFuncs
        {
        public:
            // Returns a + b
            static __declspec(dllexport) double Add(double a, double b);
    
            // Returns a - b
            static __declspec(dllexport) double Subtract(double a, double b);
    
            // Returns a * b
            static __declspec(dllexport) double Multiply(double a, double b);
    
            // Returns a / b
            // Throws DivideByZeroException if b is 0
            static __declspec(dllexport) double Divide(double a, double b);
        };
    }
    
  3. Note the __declspec(dllexport) modifier in the method declarations in this code. These modifiers enable the method to be exported by the DLL so that it can be used by other applications. For more information, see dllexport, dllimport.

  4. To create a source file for a new class, from the Project menu, select Add New Item…. The Add New Item dialog box will be displayed. On the Categories pane, under Visual C++, select Code. On the Templates pane, select C++ File (.cpp). Choose a name for the source file, such as MathFuncsDll.cpp, and click Add. A blank file will be displayed.

  5. Implement the functionality for MyMathFuncs in the source file. The code should resemble the following:

    // MathFuncsDll.cpp
    // compile with: /EHsc /LD
    
    #include "MathFuncsDll.h"
    
    #include <stdexcept>
    
    using namespace std;
    
    namespace MathFuncs
    {
        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 new invalid_argument("b cannot be zero!");
            }
    
            return a / b;
        }
    }
    
  6. To build the project into a DLL, from the Project menu, select MathFuncsDll Properties…. On the left pane, under Configuration Properties, select General. On the right pane, change the Configuration Type to Dynamic Library (.dll). Click OK to save the changes.

    NoteNote

    If you are building a project from the command line, use the /LD compiler option to specify that the output file should be a DLL. For more information, see /MD, /MT, /LD (Use Run-Time Library).

  7. Compile the dynamic link library by selecting Build Solution from the Build menu. This creates a DLL that can be used by other programs. For more information about DLLs, see DLLs.

To create an application that references the dynamic link library

  1. To create an application that will reference and use the dynamic link library that you just created, from the File menu, select New and then Project….

  2. On the Project types pane, under Visual C++, select Win32.

  3. On the Templates pane, select Win32 Console Application.

  4. Choose a name for the project, such as MyExecRefsDll, and type it in the Name field. Next to Solution, select Add to Solution from the drop down list. This will add the new project to the same solution as the dynamic link library.

  5. Click OK to start the Win32 Application Wizard. On the Overview page of the Win32 Application Wizard dialog box, click Next.

  6. On the Application Settings page of the Win32 Application Wizard, under Application type, select Console application.

  7. On the Application Settings page of the Win32 Application Wizard, under Additional options, clear the Precompiled header check box.

  8. Press Finish to create the project.

To use the functionality from the class library in the console application

  1. After you create a new console application, an empty program is created for you. The name for the source file is the same as the name that you chose for the project earlier. In this example, it is named MyExecRefsDll.cpp.

  2. To use the math routines that were created in the dynamic link library, you must reference the library. To do this, select the MyExecRefsDll project in the Solution Explorer, then select References… from the Project menu. On the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then select the Add New Reference… button. For more information about the References… dialog box, see Framework and References, Common Properties, <Projectname> Property Pages Dialog Box.

  3. The Add Reference dialog box is displayed. This dialog lists all the libraries that you can reference. The Project tab lists all the projects in the current solution and any libraries they contain. On the Projects tab, select MathFuncsDll. Then click OK.

  4. To reference the header files of the dynamic link library, you must modify the include directories path. To do this, on the Property Pages dialog box, expand the Configuration Properties node, expand the C/C++ node, and then select General. Next to Additional Include Directories, type the path of the location of the MathFuncsDll.h header file.

  5. The executable does not load dynamic link libraries until runtime. You must tell the system where to locate MathFuncsDll.dll. You do so by using the PATH environment variable. To do this, on the Property Pages dialog box, expand the Configuration Properties node and select Debugging. Next to Environment, type the following: PATH=<path of MathFuncsDll.dll file>, where <path of MathFuncsDll.dll file> is replaced with the actual location of MathFuncsDll.dll. Click OK to save all the changes.

    NoteNote

    If you want to run the executable from the command line instead of from Visual Studio, you must manually update the PATH environment variable from the command prompt as follows: set PATH=%PATH%;<path of MathFuncsDll.dll file>, where <path of MathFuncsDll.dll file> is replaced with the actual location of MathFuncsDll.dll.

  6. You can now use the MyMathFuncs class in this application. Replace the contents of MyExecRefsDll.cpp with the following code:

    // MyExecRefsDll.cpp
    // compile with: /EHsc /link MathFuncsDll.lib
    
    #include <iostream>
    
    #include "MathFuncsDll.h"
    
    using namespace std;
    
    int main()
    {
        double a = 7.4;
        int b = 99;
    
        cout << "a + b = " <<
            MathFuncs::MyMathFuncs::Add(a, b) << endl;
        cout << "a - b = " <<
            MathFuncs::MyMathFuncs::Subtract(a, b) << endl;
        cout << "a * b = " <<
            MathFuncs::MyMathFuncs::Multiply(a, b) << endl;
        cout << "a / b = " <<
            MathFuncs::MyMathFuncs::Divide(a, b) << endl;
    
        return 0;
    }
    
  7. Build the executable by selecting Build Solution from the Build menu.

To run the application

  1. Make sure MyExecRefsDll is selected as the default project. In the Solution Explorer, select MyExecRefsDll, and then select Set As StartUp Project from the Project menu.

  2. To run the project, select Start Without Debugging from the Debug menu. The output should resemble this:

    a + b = 106.4
    a - b = -91.6
    a * b = 732.6
    a / b = 0.0747475
    
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
how to call these dll functions from vb.net 2008?
can somebody give an example how to call these functions from vb.net? $0$0 $0 $0thanks$0
  • 5/13/2012
  • stn
tip
Use relative path for additional include directories (step 4 of console application) and also for the environment path to locate the dll (step 5) is easier.  You can use ..\MathFunctionsDll\ in both. The output flashes up and then disappears as the test program soon finishes. Right click the MyExecRefsDll project in your solution explorer and use Debug to step into it.
LNK2019 Error Occurred
I had created two separate solutions, rather than combining both projects under the same solution.  That led to the linkage error below.  I fixed the problem by clicking opening the MathFuncsDll existing project under the other solution, and then added the reference.  Now it works! 

Suppose if i want to do the same thing like making different solutions then how do i remove this error? what are the steps???

I cut and pasted all the code provided in the example, and added nothing else.  I used the same filenames.  But I ended up with linker error LNK2019.  The IDE is Visual Studio 2010, academic version. Here's the output:

1>MyExecRefsDll.obj : error LNK2019: unresolved external symbol "public: static double __cdecl MathFuncs::MyMathFuncs::Divide(double,double)" (?Divide@MyMathFuncs@MathFuncs@@SANNN@Z) referenced in function _main
1>MyExecRefsDll.obj : error LNK2019: unresolved external symbol "public: static double __cdecl MathFuncs::MyMathFuncs::Multiply(double,double)" (?Multiply@MyMathFuncs@MathFuncs@@SANNN@Z) referenced in function _main
1>MyExecRefsDll.obj : error LNK2019: unresolved external symbol "public: static double __cdecl MathFuncs::MyMathFuncs::Subtract(double,double)" (?Subtract@MyMathFuncs@MathFuncs@@SANNN@Z) referenced in function _main
1>MyExecRefsDll.obj : error LNK2019: unresolved external symbol "public: static double __cdecl MathFuncs::MyMathFuncs::Add(double,double)" (?Add@MyMathFuncs@MathFuncs@@SANNN@Z) referenced in function _main
1>C:\Visual Studio Applications\MyExecRefsDll.cpp\Debug\MyExecRefsDll.cpp.exe : fatal error LNK1120: 4 unresolved externals
cant register the dll
regsvr32 fails with the dll. $0In going through the tutorial and seeing the problems others have I get the clear sense that no one at MS cares very much about $0 $0anyone getting work done.$0
No dll or lib
Followed all the steps. $0Redid it many times with many types of projects...$0 $0$0 $0There is no dll, no lib, no nothing in the debug folder nor the release folder.$0 $0Just a bunch of log and obj files.$0 $0$0 $0 $0I mean, in the configurations, it's specified that the output is gonna be a dll.$0 $0The build succeeded...$0 $0$0 $0 $0So.. where is it? O.o  Was it just false advertising? :($0 $0 $0$0 $0 $0Edit : FOUND IT.  In c# or vb, your dll will appear in the debug or release folder of the project.  BUT for c++, they are created in the debug/release folder of the SOLUTION.  So go back one folder and you should find it.$0
Re: Link looks for .lib instead of .dll file
> I have gone through the steps, created a .dll, but when I tried to link, I got a message saying it couldn't find the .lib file.  Does anyone know what I am missing?

I have the same problem...
Maybe it's explained here? http://stackoverflow.com/questions/1297013/why-do-we-still-need-a-lib-stub-file-when-weve-got-the-actual-dll-implementati
If that's the case, why MS didn't explain that??!

After trying creating a non-empty project I've also found this inside the readme.txt file:
[...]
myDLLproject.cpp
    This is the main DLL source file.

    When created, this DLL does not export any symbols. As a result, it
    will not produce a .lib file when it is built. If you wish this project
    to be a project dependency of some other project, you will either need to
    add code to export some symbols from the DLL so that an export library
    will be produced, or you can set the Ignore Input Library property to Yes
    on the General propert page of the Linker folder in the project's Property
    Pages dialog box.
[...]
Using this example DLL in VB.NET 2008?
I would love to see an example of how to use this example's created DLL in Visual Basic 2008 Express. I would also like to add that this walk through on how to create a DLL in Visual C++ 2008 Express is the most informative and detailed one I have seen. Thank you! $0$0 $0 $0Hop (Hopworks)$0
Slight change for VS2008
I used VS2008. The 1st time I followed the walkthrough exactly, but the compilation of MyExecRefsDll.cpp failed. $0So I changed the steps of creating MyExecRefsDll.cpp slightly:$0 $01)To create an application that will reference and use the dynamic link library that you just created, from the File menu, select New and then Project$0 $02)On the Project types pane, under Visual C++, select Win32.$0 $03)On the Templates pane, select Win32 Console Application.$0 $04)Choose a name for the project, such as MyExecRefsDll, and type it in the Name field. Next to Solution, select Add to Solution from the drop down list. This will add the new project to the same solution as the dynamic link library.$0 $05)Click OK to start the Win32 Application Wizard. On the Overview page of the Win32 Application Wizard dialog box, click Next.$0 $06)On the Application Settings page of the Win32 Application Wizard, under Application type, select Console application.$0 $07)On the Application Settings page of the Win32 Application Wizard, under Additional options, clear the Precompiled header check box.$0 $08)On the Application Settings page of the Win32 Application Wizard, under Additional options, select Empty project.$0 $09)Press Finish to create the project.$0 $0$0 $0(NOTE: Step 8 is the addition!)$0 $0$0 $0 $0Then I add MyExecRefsDll.cpp as a new item to the MyExecRefsDll project, and fill its content as the walkthrough says.  Then the build is working perfectly!$0 $0$0 $0 $0Cheers!$0
Works Perfectly
Thanks for the walk-through. It worked perfectly for me. Only thing to keep in mind is that both projects should contain the header otherwise your program would not compile & run.
Link looks for .lib instead of .dll file
I have gone through the steps, created a .dll, but when I tried to link, I got a message saying it couldn't find the .lib file.  Does anyone know what I am missing?
There is no problem in given information"Creating and Using a Dynamic Link Library (C++)"
Its run fine, if anyone not able to find path then  in point number 6 do some little changes in place of
#include "MathFuncsDll.h"  
provide complete path of your "mathFuncsDll.h" like #include "D:\MathFuncsDll\MathFuncsDllNew.h"and then
Rebuild MathFuncsDll and MyExecRefsDll and Run.
Errata corrige
> I hope someone can explain what is going on.

Guideline is wrong: replace the step 3 instruction "select Win32 Console Application" with "select Win32 Project"
(look at http://social.msdn.microsoft.com/Forums/en-CA/Vsexpressvc/thread/8614e913-06a1-4646-a734-e4f596618c3d)
I am having the same problem with the missing DLL
I hope someone can explain what is going on.
Can't find the .dll file after building the solution.
After building the solution i am unable to find the .dll file rather it is showing .obj and .pdb files.. please help me , i want to use that dll as password filter for LSA.
access this dll in a VB2010 class?


I too am having trouble getting my VC++ 2010 .dll to work in
another class project.  Just so happens
mine is a VB2010 class project.  Can
anyone provide a link to how to I can do this? 
I cannot make a reference to the VC++ project or .dll, even though the
project is within my solution of VB projects.

How does one invoke this DLL from a C# app?
Happily your walkthrough example works when the client is also C++ Win32 app.  I tried following a parallel approach using a C# app (referring to the C++ Wind32 DLL, but it cannot get it work.

Is there a walkthrough example for accessing a C++ Win32 (MathFun) DLL from a C# client app (preferably a WinForm .Net 4.0)?
Advertisement