Source : ct|23.04.08
< Tutorials Computer, Multimedia, Chinese
A static library (file extension .a or .lib) is a file containing functions which will be integrated to the executable file after the linking phase. On the contrary, a dynamic library (extension .dll) is a file containing functions who will not be integrated to the executable file after the linking phase; in that case, the excutable file will call the DLL library, during the execution phase, to obtain the wished functions..
In the present tutorial, we will learn to create and use a C static library. After we will use that library in a C++ program. To realize this work, we will use the free (GNU GPL) development environment CodeBlocks. The development environments Devcpp or Visual Studio C++ permit to obtain the same result.
Run Codeblocks and create a new project of type "Static Library" (File/New/Project/Static Library/Go).
Give a name to your project ("malibrairie" for instance ), and assign it a destination directory ("C:/essai" for instance )
Delete the default code in the file "main cpp" of the library, and type the following code. This code correspond to a simple example function which multiplies (by 5) a number (the address of this number is passed in parameter to the funtion).
void cinq(int *i)
{
int n;
n=*i;n=5*n;
*i=n;
}
Click the menu option "Build/Run".
Immediately Codeblocks generates the library file in the "C:/essai/malibrairie" directory and gives it the name "libmalibrairie a".
You can remark that Codeblocks and Devcpp give an extension ".a" to the libraries, when Visual Studio gives them an extension ".lib". That is not a problem.
We will now use, with a C++ program, the library "libmalibrairie.a" that we have create.
Create a new project with the type "Win32 GUI".
Choose an application type "Frame based".
Give it a name ("monprogramme" for instance ) and a destination directory ("C:/essai" for instance).
Delete the generated default code, in the file "main cpp" of this new project, and replace it with the following source code ( more short and simply) to test our library :
#include "windows.h"
extern "C" void cinq (int *);
int APIENTRY WinMain(HINSTANCE h1,HINSTANCE h2,LPSTR l,int n)
{
int x;
char texte[80];
x=2;
cinq(&x);
wsprintf(texte,"%d",x);
MessageBox(NULL,texte,"",MB_OK);
return 0;
}
Normally, Codeblocks does not know the library file used, neither his location. We must also declare the library file so that, the compilation and the link phase can be proceed without displaying errors. For that, choose the menu option "Project/Build options/Linker Settings" and add to the project, in the window "link libraries:", the path to your library file "libmalibrairie.a" then click "OK".
Click "Build/Build and run". The compilation and the link phases are executed and integrate in the executable file the necessary functions existing in the static library.Then your programme runs. We obtain well 5x2=10... It works correctly.
© http://turrier.fr (2007) |