Share the ideas and thoughts, become united ...

Saturday, October 20, 2012

Implicitly linking DLL with VS2010 or earlier

You may be wondering what is "Implicit DLL linking". There are two way to link to a DLL one is "Implicit" another one is "explicit".
When you are the builder of the DLL or you have the exported symbol definition file or the exported lib, you can add the DLL simply by incorporating the .DEF (definition file) or the .lib file to the project properties.
But when you do not have the any of the things mentioned above, you have to load the DLL explicitly by using "LoadLibrary" win32 API, get the function pointer by calling "GetProcAddress" and the calling the function using the function pointer.
Today I am going to discuss how to "Implicit" link DLL file into your application.
First open a DLL project - usually a win32 project.

win32 DLL project window

Then select DLL from the next window to open the project as a DLL project.
Next I am going to add a header file called Math.h and add some basic function there. which I will export through DLL and use it in a console application.
the Math.h file
#pragma once
class __declspec(dllexport) Math {
public:
    int add(int a, int b);
    double sqr(double a);
}
and the cpp file
#include "Math.h"
int Math::add(int a, int b) {
    return (a+b);
}
double Math::sqr(double a) {
    return (a*a);
}
__declspec(dllexport) will tell the compiler that this class should be exported by the DLL for use in application.
Building this project will generate two components.
1. the DLL file itselfv [myDLL.dll]
2. a lib file which holds the necessary stubs and initializations to call appropriate DLL function  [myDLL.lib]
to incorporate DLL into an application one has to include the .lib into project dependencies.


Thats all. Now you can build your application and use the DLL function very easily.
Hope this helps.
If you have any queries or suggestions, please leave a comment.