Home

Using Additional Libraries

 

Custom Libraries

 

Introduction

A library is a group of functions, classes, or other resources that can be made available to programs that need already implemented entities without the need to know how these functions, classes, or resources were created or how they function. Although a library can appear as a complete program, in the strict sense, it is not. For example, it cannot be executed by a casual user and it cannot execute its own program. A library makes it easy for a programmer to use a function or functions, a class or classes, a resource or resources created by another person or company and trust that this external source is reliable and efficient. Although the issue or creating or implementing a library may appear intimidating, it is absolutely not.

There are only two difficult aspects of a library: 1)Why do you need a library? And what do you want to put in a library? As you see, these two "difficult" aspects we mention have nothing to do with programming. We can also state that we do not have an answer to either of these questions: it will be up to you. What we will do here is to show HOW to create a library, not why. We will also show how to include things in a library. We will not define WHY you should put this function and not that one in a library because, from our experience, it always depends on the programmer, the project, or a group of people working on an application.

Libraries Characteristics

A library is created and functions like a normal regular program, using functions or other resources and communicating with other programs. To implement its functionality, a library contains functions that other programs would need to complete their functionality. At the same time, a library may use some functions that other programs would not need. For this reason, there are two types of functions you will create or include in your libraries. An internal function is one used only by the library itself: the program that uses the library, also called the client of the library, will not need access to these functions. External functions are those that can be accessed by the clients of the library.

There are two broad categories of libraries you will deal with in your programs: static libraries and dynamic libraries. The process of creating each makes the biggest difference, not necessarily their functionalities. Even so, there are various techniques used to create each category (once again, we insist on stating that the process of creating a library will be the least difficult of your tasks).

Static Libraries

 

Introduction

A static library is a file that contains functions, classes, or resources that an external program can use to complement its functionality. To use a library, the programmer has to create a link to it. The project can be a console application, a Win32 or a VCL application. The library file has the lib extension.

To create a static library, you can open the New Items dialog box and select Library as the type of application. In the Win32 Application Wizard, select the Static Library radio button in the Application Type section. After laying the foundation of a static library, you can add functions, classes, and/or resources that will be part of the library.

Practical Learning Practical Learning: Introducing Keyboard Messages

  1. Start Borland C++ Builder and, on the main menu, click File -> New -> Other...
  2. In  the Item Categories list, click C++Builder Projects
  3. In the right list, click Static Library
     
    New Items
  4. Click OK
  5. To save the project, on the Standard toolbar, click the Save All button
  6. In the Save Project As dialog box, click the Create New Folder button to create a new folder
  7. Type BusMath and press Enter twice to display the new folder in the Save combo box
  8. Replace the name of the project with BusinessMath and click Save
  9. To add a new unit, on the main menu, click File -> New -> Unit - C++Builder
  10. To save the new unit, on the Standard toolbar, click the Save All button
  11. Replace the content of the Name edit box with bmcalc and click Save
  12. In the header file, declare the following functions:
     
    //---------------------------------------------------------------------------
    #ifndef bmcalcH
    #define bmcalcH
    //---------------------------------------------------------------------------
    double __fastcall Average(const double *Numbers, const int Count);
    long   __fastcall GreatestCommonDivisor(long Nbr1, long Nbr2);
    //---------------------------------------------------------------------------
    #endif
  13. In the source file, implement the functions as follows:
     
    //---------------------------------------------------------------------------
    
    #pragma hdrstop
    
    #include "bmcalc.h"
    
    //---------------------------------------------------------------------------
    
    #pragma package(smart_init)
    double __fastcall Average(const double *Nbr, const int Total)
    {
    	double avg, S = 0;
    
    	for(int i = 0; i < Total; i++)
    		S += Nbr[i];
    
    	avg = S / Total;
    	return avg;
    }
    //---------------------------------------------------------------------------
    long __fastcall GreatestCommonDivisor(long Nbr1, long Nbr2)
    {
    	while( true )
    	{
    		Nbr1 = Nbr1 % Nbr2;
    		if( Nbr1 == 0 )
    			return Nbr2;
    
    		Nbr2 = Nbr2 % Nbr1;
    		if( Nbr2 == 0 )
    			return Nbr1;
    	}
    }
    //---------------------------------------------------------------------------
  14. To create the library, on the main menu, click Project -> Build BusinessMath
     
    Compiling
  15. When the library has been built, click OK on the Compiling dialog box
  16. Save All

Testing the Static Library on the Console

A static library created can be used by either a console application, a Win32 application, or a VCL application. That's one of its advantages

Practical Learning Practical Learning: Testing the Library on a Console Application

  1. To create a console application, on the main menu, click File -> New -> Other...
  2. In the New property page of the New Items dialog box, click Console Wizard and click OK
  3. In the Console Wizard dialog box, make sure the C++ radio button and the Console Application check box are selected
     
    New Console Application
  4. Click OK
  5. To save the new project, on the Standard toolbar, click the Save All button
  6. Click the Create New Folder button. Type BusMathTest1 and press Enter twice
  7. Replace the name of Unit with Exercise
  8. Replace the name of the project with BusMathTest and press Enter
  9. Open Windows Explorer or My Computer
  10. Locate the folder that contains the above project: BusMath. Click the BusinessMath.lib file. Press and hold Ctrl, then click the bmcalc.h header file
  11. Press Ctrl + C to copy them
  12. Locate the BusMathTest1 folder. Right-click it and click Paste to paste both the BusinessMath.lib and the bmcalc files in the same folder that contains Exercise.cpp
  13. Back in C++ Builder, to add the library to the current project, on the main menu, click Project -> Add To Project...
  14. In the Files of Type combo box, select Library Files (.lib)
  15. In the list of files, click BusinessMath.lib
     
    Add to Project
  16. Click OK
  17. Type the following in the empty Exercise.cpp file
     
    //---------------------------------------------------------------------------
    #include <iostream>
    #include <conio>
    using namespace std;
    #pragma hdrstop
    #include "bmcalc.h"
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        double Numbers[] = { 12.55, 94.68, 8.18, 60.37, 104.502, 75.05 };
        int Count = sizeof(Numbers) / sizeof(double);
    
        double Avg = Average(Numbers, Count);
    
        cout << "Average of the list: " << Avg;
    
        cout << "\n\nPress any key to continue...";
        getch();
        return 0;
    }
    //---------------------------------------------------------------------------
  18. Save All
  19. Press F9 to test the application:
     
    Average of the list: 59.222
    
    Press any key to continue...
  20. Close it and return to Borland C++ Builder

Testing the Static Library on a GUI Application

 

Practical Learning Practical Learning: Testing the Static Library on a GUI Application

  1. To test the library with a GUI application, on the main menu, click File -> New -> Application
  2. To save the new project, on the Standard toolbar, click the Save All button
  3. Click the Create New Folder button. Type BusMathTest2 and press Enter twice
  4. Replace the name of the unit with Main
  5. Set the name of the project to BusMathTest and press Enter
  6. In Windows Explorer or My Computer, copy the BusinessMath.lib and the bmcalc.h files from the BusMath folder to the BusMathTest2 folder
  7. Then, on the main menu in C++ Builder, click Project -> Add To Project... Change the Files of Types to Library Files (.lib). Select he BusinessMath.lib file and press Enter
  8. Design the dialog box as follows:
     
    Business Mathematics
    Control  Caption or Text Name Other Properties
    Form Business Mathematics frmMain BorderStyle: bsDialog
    Label Number &1:    
    Edit 1 edtNumber1  
    Label Number &2:    
    Edit 1 edtNumber2  
    BitBtn C&alculate btnCalculate  
    Label GCD:    
    Edit   edtGCD  
    BitBtn     Kind: bkClose
  9. On the form, double-click the Calculate button to access its OnClick event
  10. Implement the event as follows:
     
    //---------------------------------------------------------------------------
    #include <vcl.h>
    #pragma hdrstop
    
    #include "Main.h"
    #include "bmcalc.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    #pragma resource "*.dfm"
    TfrmMain *frmMain;
    long   __fastcall GreatestCommonDivisor(long Nbr1, long Nbr2);
    //---------------------------------------------------------------------------
    __fastcall TfrmMain::TfrmMain(TComponent* Owner)
        : TForm(Owner)
    {
    }
    //---------------------------------------------------------------------------
    void __fastcall TfrmMain::btnCalculateClick(TObject *Sender)
    {
        int Nbr1, Nbr2, Result;
    
        Nbr1 = atoi(edtNumber1->Text.c_str());
        Nbr2 = atoi(edtNumber2->Text.c_str());
    	
        Result = GreatestCommonDivisor(Nbr1, Nbr2);
    
        edtGCD->Text = IntToStr(Result);
    }
    //---------------------------------------------------------------------------
  11. Test the application. Here is an example:
     
  12. Close it and return to MSVC

Creating a Dynamic Link Library

 

Introduction

A dynamic link library or DLL is a program that another program needs for its functionality. It usually has an extension of .dll although it could sometimes have another extension. DLLs are created for various reasons, the most regular of which allows different programs to "call" the same DLL.

Practical Learning Practical Learning: 

  1. Start Borland C++ Builder if you didn't yet. On the main menu, click File -> New -> Other...
  2. In the Item Categories list, click C++Builder Projects
  3. In the right list, click Dynamic-Link Library
     
  4. Click OK.
  5. On the DLL Wizard, click the C++ radio button and only the Use VCL check box
     
  6. Click OK
  7. To save the current project, on the main menu, click File -> Save All
  8. To make things easier, from the Save Unit1 As dialog box, locate the common folder called Programs and display it in the Save In combo box.
  9. Click the Create New Folder button, type DLLExercise and press Enter.
  10. Double-click the new folder to display it in the Save In combo box. In the File Name edit box, change the name of the unit to DLLUnit and click Save.
  11. Change the name of the project to DLLProject and click Save.
  12. Examine and read the whole file, especially the commented section.
  13. On top of the DLLEntryPoint() function, declare the needed functions and implement them as follows:
     
    //---------------------------------------------------------------------------
    #include <vcl.h>
    #include <windows.h>
    #pragma hdrstop
    //---------------------------------------------------------------------------
    #pragma argsused
    //---------------------------------------------------------------------------
    // This function is used to calculate the total area of a parallelepid rect
    double BoxArea(double L, double H, double W);
    // This function is used to calculate the volume of a parallelepid rectangle
    double BoxVolume(double L, double H, double W);
    //---------------------------------------------------------------------------
    int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
    {
        return 1;
    }
    //---------------------------------------------------------------------------
    double BoxArea(double L, double H, double W)
    {
        return 2 * ((L*H) + (L*W) + (H*W));
    }
    //---------------------------------------------------------------------------
    double BoxVolume(double L, double H, double W)
    {
        return L * H * W;
    }
    //---------------------------------------------------------------------------
  14. Because the above functions cannot be accessed from outside the DLL, we will provide a function that can pass data from outside and to the external programs.
    Declare such a function as follows:
     
    //---------------------------------------------------------------------------
    #include <vcl.h>
    #include <windows.h>
    #pragma hdrstop
    //---------------------------------------------------------------------------
    #pragma argsused
    //---------------------------------------------------------------------------
    // This function is used to calculate the total area of a parallelepid rect
    double BoxArea(double L, double H, double W);
    // This function is used to calculate the volume of a rectangular parallelepid
    double BoxVolume(double L, double H, double W);
    // This function is used to get the dimensions of a rectangular parallelepid
    // calculate the area and volume, then pass the calculated values to the
    // function that called it.
    extern "C" __declspec(dllexport)void BoxProperties(double Length, double Height,
                                        double Width, double& Area, double& Volume);
    //---------------------------------------------------------------------------
    int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
    {
        return 1;
    }
    //---------------------------------------------------------------------------
    double BoxArea(double L, double H, double W)
    {
        return 2 * ((L*H) + (L*W) + (H*W));
    }
    //---------------------------------------------------------------------------
    double BoxVolume(double L, double H, double W)
    {
        return L * H * W;
    }
    //---------------------------------------------------------------------------
    void BoxProperties(double L, double H, double W, double& A, double& V)
    {
        A = BoxArea(L, H, W);
        V = BoxVolume(L, H, W);
    }
    //---------------------------------------------------------------------------
  15. To save your project, on the main menu, click File -> Save All.
  16. To build the DLL, on the main menu, click Project -> Build DLLProject. During the building process, a dialog box will display the evolution. If there is a mistake somewhere, correct it. When everything goes fine, the dialog box will disappear.
  17. To get the DLL ready for use, you will have to import it using the Implib utility. To do that, access the Command Prompt (it depends on the operating system you are using. In Win2000/XP you can click Start -> Programs -> Accessories -> Command Prompt). Type CD\ to remove whatever directory is displaying.
  18. Display the directory where the DLL project was created. For this exercise, this would be:
    C:\Programs\DLLExercise (this means you will type CD Programs\DLLExercise).
  19. Once you are inside the folder of the DLL project, type implib DLLProject.lib DLLProject.dll and press Enter
     
  20. When the DLL has been imported, type Exit and press Enter
  21. Save your project

A Project That Uses the DLL

Now we will create a project to use our DLL. Although our DLL can be used in any program, we will first implement it in a VCL application.

Practical Learning Practical Learning: Using a DLL in a Project

  1. On the main menu, click File -> New -> VCL Forms Application
  2. To save the project, on the main menu, click File -> Save All.
  3. Locate and display the same folder in which the DLL project was created.
  4. Save the unit as Main and the project as ParaRect
  5. Design the form as follows:
     
  6. Besides the labels you can read, from top -> down, the form has five Edit controls named edtLength, edtHeight, edtWidth, edtArea, and edtVolume respectively. Then add two buttons named btnCalculate and btnExit.
  7. To add the DLL to the current project, on the main menu, click Project -> Add To Project...
  8. From the Add To Project dialog box, click DLLUnit and click OK
  9. On the form, double-click the Exit button and implement its OnClick event as follows:
     
    //---------------------------------------------------------------------------
    void __fastcall TForm1::btnExitClick(TObject *Sender)
    {
        Close();
    }
    //---------------------------------------------------------------------------
  10. On the form, double-click the Calculate button.
  11. To call the DLL, change the file as follows:
     
    //---------------------------------------------------------------------------
    #include <vcl.h>
    #pragma hdrstop
    
    #include "Main.h"
    //---------------------------------------------------------------------------
    #pragma package(smart_init)
    #pragma resource "*.dfm"
    TForm1 *Form1;
    //---------------------------------------------------------------------------
    extern "C" __declspec(dllimport)void BoxProperties(double L, double H,
                                        double W, double& A, double& V);
    //---------------------------------------------------------------------------
    __fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
    {
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::btnExitClick(TObject *Sender)
    {
        Close();
    }
    //---------------------------------------------------------------------------
    void __fastcall TForm1::btnCalcultateClick(TObject *Sender)
    {
        double Length, Height, Width, Area, Volume;
    
        Length = edtLength->Text.ToDouble();
        Height = edtHeight->Text.ToDouble();
        Width = edtWidth->Text.ToDouble();
    
        BoxProperties(Length, Height, Width, Area, Volume);
    
        edtArea->Text = Area;
        edtVolume->Text = Volume;
    }
    //---------------------------------------------------------------------------
  12. To save the project, on the main menu, click File -> Save All
  13. To execute the project, on the main menu, click Run -> Run

Testing the DLL

At this time, our DLL is distributable. You can pass it to another programmer and give just small instructions on how to use it. As an example, we will call it from a console application.

Practical Learning Practical Learning: Testing a DLL

  1. Open Windows Explorer and display the content of the folder in which the DLL project was created.
  2. On the right pane, click the file with .dll extension. Press and hold Ctrl. Click the file with extension .lib.
  3. After making sure that both files are selected, on the main menu of Windows Explorer, click Edit -> Copy. Close Windows Explorer.
  4. In C++ Builder, to start a new project, on the main menu, click File -> New.
  5. On the New Items dialog box, click Console Wizard and click OK.
  6. On the Console Wizard dialog box, click the C++ radio button, the Use VCL, and the Console Application check boxes. Click OK.
  7. To save the current project, on the main menu, click File -> Save All.
  8. Locate and display the Programs folder. double-click the Borland C++ Builder folder to display it in the Save In combo box.
  9. Click the Create New Folder button, type Consoler and press Enter
  10. Double-click the new folder to display it in the Save In combo box.
  11. As the Consoler folder displays in the Save In combo box, right-click the main empty area and click Paste
  12. It will look like nothing happened. Click the arrow of the Files Of Type combo box and select All Files. Depending on how your computer is set up to display extensions, you should have two new files: DLLProject.dll and DLLProject.lib
  13. Click the arrow of the Files Of Type combo box again and select C++ Builder Unit (*.cpp).
  14. In the File Name, change the content to Main and click Save
  15. To change the name of the project, type Consoler and click Save
  16. To add the DLL to the current project, on the main menu, click Project -> Add To Project...
  17. Click the arrow of the Files Of Type combo box and select Library File (*.lib)
  18. Click the only file displaying: DLLProject
  19. Click Open
  20. To call the DLL, change the content of the Main.cpp file as follows:
     
    //---------------------------------------------------------------------------
    #include <iostream.h>
    #include <vcl.h>
    #pragma hdrstop
    //---------------------------------------------------------------------------
    extern "C" __declspec(dllimport)void BoxProperties(double L, double H,
                                        double W, double& A, double& V);
    //---------------------------------------------------------------------------
    
    #pragma argsused
    int main(int argc, char* argv[])
    {
        double Length, Height, Width, Area, Volume;
    
        cout << "Enter the dimensions of the box\n";
        cout << "Length: ";
        cin >> Length;
        cout << "Height: ";
        cin >> Height;
        cout << "Width: ";
        cin >> Width;
    
        BoxProperties(Length, Height, Width, Area, Volume);
    
        cout << "\nProperties of the box";
        cout << "\nLength:  " << Length;
        cout << "\nHeight:  " << Height;
        cout << "\nWidth:   " << Width;
        cout << "\nArea:    " << Area;
        cout << "\nVolumne: " << Volume;
    
        cout << "\n\nPress any key to continue...";
        getchar();
        return 0;
    }
    //---------------------------------------------------------------------------
  21. To execute the project, on the main menu, click Run -> Run

 

Previous Copyright 2005-2007 Yevol Next