Creation and use of static connection libraries

xiaoxiao2021-03-06  59

9.2 Static connection library

9.2.1 Creating a static library

Now use a simple mathematical library as an example to introduce the creation and use of static libraries.

To create a static library, select the File-> New menu, pop up the New dialog box. Select the Projects tab, select Win32 Static Library in the Project Types list box, enter MyMath in Name, indicating a static library file to create a mymath.lib.

Then use the Project-> Add to Project-> Files menu to add the following two files to mymath:

1. Header file (see Listing 9.1): Define two functions of Summary and Factorial, which are used to complete the summary and level. Note that the function of the C style is used here, you need to add the extern "C" keyword, indicating that it is an external function of the C style.

Listing 9.1 header file

#ifndef _MYMATH_H

#define _mymath_h

EXTERN "C"

{

Int Summary (int N);

INT FACTORIAL (INT N);

}

#ENDIF

2. Source file: Contains the definition of the Summary and Factorial functions, see Listing 9.2.

Listing 9.2 Source file

Int Summary (INT N)

{

INT SUM = 0;

INT I;

For (i = 1; i <= n; i )

{

SUM = I;

}

Return SUM;

}

INT FACTORIAL (INT N)

{

INT FACT = 1;

INT I;

For (i = 1; i <= n; i )

{

FACT = FACT * I;

}

Return Fact;

}

Under the Build menu, select Build MyMath.lib under the build menu. Visual C compiles the link project to generate a MyMath.lib file in mymath / debug directory. At this point, the work generated by the static connection library is done. Below with a small program to test this static library.

Tip: When the user delivers the final static connection library, only the .lib file and header file are required, and no source code for the library is required.

9.2.2 Test Static Library

Generate a dialog-based application TEST with AppWizard. Open the TEST resource file, modify the IDD_TEST_DIALOG dialog, join the two buttons. Button ID and text are:

IDC_SUM "& summary"

IDC_FACTORIAL "& Factorial"

As shown in Figure 9-1.

Figure 9-1 Modifying Test dialog

Use classwizard to generate messages handlers ONSUM and ONFACTORAL for the above two button Click events, and add code, modified ONSUM and ONFactorial see Listing 9.3.

Listing 9.3 ONSUM and ONFACTORIAL function definition

Void ctestdlg :: ONSUM ()

{

// Todo: Add Your Control Notification Handler Code Here

INT nsum = summary (10);

Cstring SResult;

SResult.Format ("SUM (10) =% D", NSUM;

AfxMessageBox (SRESULT);

}

Void ctestdlg :: onfactorial ()

{

// Todo: Add Your Control Notification Handler Code Here

INT nfact = factorial (10);

Cstring SResult;

SResult.Format ("10! =% D", NFACT); AFXMessageBox (SRESULT);

}

Because of the functions in mymath.lib, you must first put two files for mymath.lib and mymath.h.

转载请注明原文地址:https://www.9cbs.com/read-118831.html

New Post(0)