Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++ using G++) Create a DLL

 

Before being able to call a DLL, one has to create a DLL first.

 

To create a DLL using G++, do the following steps:

  • Create a DLL entry point with a WinMain

  • Create a unit with the functions you want to put in a DLL

  • Build the DLL

     

    UnitEntryPoint.cpp

     

    //---------------------------------------------------------------------------

    #include <windows.h>

    //---------------------------------------------------------------------------

    int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)

    {

    return 1;

    }

    //---------------------------------------------------------------------------

    int WINAPI WinMain(

    HINSTANCE hInstance,

    HINSTANCE hPrevInstance,

    LPSTR lpCmdLine,

    int nCmdShow)

    {

    return 0;

    }

    //---------------------------------------------------------------------------

     

     

    *        View this code in plain text.

     

     

    UnitFunctions.h

     

     

    //---------------------------------------------------------------------------

    #ifndef UnitFunctionsH

    #define UnitFunctionsH

    //---------------------------------------------------------------------------

    #ifdef __cplusplus

    extern "C"

    {

    #endif

     

    __declspec (dllexport) const int GetAnswerOfLife();

     

    #ifdef __cplusplus

    }

    #endif

     

    //---------------------------------------------------------------------------

    #endif

     

     

    *        View this code in plain text

     

    The function put in the DLL is called GetAnswerOfLife and will return the value of 42. Note the #ifdef's before and after the function. These are obligatory!

     

    Now the function GetAnswerOfLife must be defined in UnitFunctions.cpp. Upon viewing it, the code looks like below

     

    UnitFunctions.cpp

     

     

    //---------------------------------------------------------------------------

    #include "UnitFunctions.h"

    //---------------------------------------------------------------------------

    const int GetAnswerOfLife()

    {

    return 42;

    }

    //---------------------------------------------------------------------------

     

     

    *        View this code in plain text.

     

    Building the DLL

     

    Use the following G++ commands:

     

     

    g++ -c UnitFunctions.cpp

    g++ -c UnitEntryPoint.cpp

    g++ -o Functions.dll UnitEntryPoint.o UnitFunctions.o

     

     

    This should yield your first DLL!

     

    Perhaps you now want to go to the calling a DLL page.

     

    Or download all source code of this page at once.

     

     

     

    Go back to Richel Bilderbeek's C++ page.

    Go back to Richel Bilderbeek's homepage.