Thursday, 21 March 2013

Creating and using a Dll from Empty project

It is very important to know that how cane we create a Dll from an empty project and how can we use it.

Creating a library:-

We can create it by following steps:-

1)Create an empty project into the visual studio.


2)We need the function with the following syantax.


#include<iostream>
#include <cstdio> // instead of <stdio.h>
#include <cstdlib> // instead of <stdlib.h>
 #include <conio.h> //-- do not use

#include <cstring> // instead of <string.h>
using namespace std;

//C++ style header decoration in the dll
  __declspec(dllexport)  int __stdcall add(int a ,int b )
{
 return a+b;
}
//c style header declartion in the dll
 extern "C"  __declspec(dllexport) int  _stdcall sub(int a ,int b )
{
 return a-b;
}
//C++ style header decoration in the dll
  __declspec(dllexport)int _cdecl mul(int a ,int b )
{
 return a*b;
}
//c style header declartion in the dll
extern "C" __declspec(dllexport)int  _cdecl divide(int a ,int b )
{
 return a/b;
}


3)Now, we need to follow these steps:-
 project properties -> general->project defaults ->configuration type->choose dynamic library(.dll)


4)Then we need to build it .After building it the .lib file is generated .

(5)Now we Can use these functions into other files by including .lib file and header files into that project.

Using the created library: -.We can use the created library by adding this .lib file to that project in which we want to use it.We need to create a new project and call the functions in that project after adding the library.We need to write following code for using this library.


#include<iostream>
using namespace std;

//C++ style header decoration in the dll
int __stdcall add(int a ,int b );

//C style header declartion in the dll
extern "C" int  _stdcall sub(int a ,int b );

//C++ style header decoration in the dll
int _cdecl mul(int a ,int b );

//C style header declartion in the dll
extern "C" int  _cdecl divide(int a ,int b );

void main()
{
 cout<<add(3,4);
 cout<<sub(4,3);
 cout<<mul(3,4);
 cout<<divide(4,2);
}



There are two methods to adding the .lib fie:-

1)We need to go to add->existing item->choose .lib file
2)
(a)In the project property  Go to  VC++ Directories   .In librery Directories add the  full path where the .lib is placed.



(b)n the linker -->Input-->additional Dependencies -->add the .lib file of the dll generated.



Now we can easily use the library by adding any of these two methods.

*.lib function is required to build the function and .dll and .lib both required for the execution of the program.

No comments:

Post a Comment