jeudi 26 février 2015
Create a DLL using C - CL.EXE Compiler
Just to create a DLL file using C language, you need to create three files :- Library header (.h)
- Library Source (.c) : will be compiled to build the DLL
- Main Program (.c) : this is the source of the program that will use the DLL
1 - Library Header: mydll.h
In this step we have to create a mydll.h file that we will declare in the functions that we will use in our program.
__declspec(dllexport) float add_func(float x, float y);
__declspec(dllexport) float sub_func(float x, float y);
__declspec(dllexport) float mul_func(float x, float y);
__declspec(dllexport) float div_func(float x, float y);
In this file, we must include the "Library Header" then define our functions like this example :
#include
"mydll.h"
float add_func(float x, float y)
{
return x + y;
}
float sub_func(float x, float y)
{
return x - y;
}
float mul_func(float x, float y)
{
return x * y;
}
float div_func(float x, float y)
{
if(y != 0)
return x / y;
else
return -1; //Returns -1 if y == 0
}
3 - Library Source: calcul.c
This is program that will use the dll, we must include the needed headers including "Library Header", we will use <stdio.h> header and "mydll.h" then use the function
#include
<stdio.h>
#include
"mydll.h"
int main()
{
float x, y;
printf("Enter two numbers:");
scanf("%f
%f", &x, &y);
printf("ADD:
%f\n", add_func(x, y) );
printf("SUB:
%f\n", sub_func(x, y) );
printf("MUL:
%f\n", mul_func(x, y) );
printf("DIV: %f\n", div_func(x, y) );
return 0;
}
Now we are going to compile all of that using CL compiler
DLL Compiling:
To compile the DLL using CL Compiler, we need the name of "Library Source", in our example the name of that is mydll.c:
cl /LD mydll.c
the /LD flag is the flag that create the DLL with other needed files.
You can see that "mydll.dll" generated successfully with other files.
EXE Compiling :
We almost complished our mission.
Now you need to compile the "calcul.c" to build our program, using this command :
cl calcul.c mydll.lib
You can see that we have used "mydll.lib" that help us to build the program.
Now you can keep just calcul.exe and mydll.dll then remove other files .
Finally run the program:
Related Posts
Inscription à :
Publier les commentaires
(
Atom
)
Aucun commentaire :
Enregistrer un commentaire