Creating a DLL using Visual Studio is pretty easy. Create a New Project, and specify DLL as application type.
A DLL may have a sort of main function, that is called at startup and it is a good place where to put initialization code. Let's see here a possible implementation for such a function, that we are about to use just to print a log message when the DLL process is loaded:
BOOL APIENTRY DllMain( HMODULE hModule,
LPVOID lpReserved )
std::cout << "DLL process attached" << std::endl;
To make available functions to the user code, we write an header file where we put the function declarations:
#define XDLL_API extern "C" __declspec(dllimport)
XDLL_API void f();
We define a symbol (here we call it XDLL_API) that is a declaration specification for the functions. When we include this header in the application using the DLL, XDLL_API has not previously defined, so we use the definition here available, that specify that the functions are "dllimport".
Here is how we define a function in a DLL:
// XDLL_API defined for export
#define XDLL_API extern "C" __declspec(dllexport)
std::cout << "Hello from DLL" << std::endl;
Before including the header file containg the prototypes, we provide an alternative definition for the XDLL_API symbol, that is going to be used in the DLL. Notice that in the function definition we don't even use it - it is not necessary, since the compiler is smart enough to match the declaration with the definition even if we don't duplicate the declaration specification.
Basically, that's all. We compile, and we have a DLL ready to be used by other applications.