9.2静态连接库 9.2.1创建静态库 现在以一个简单的数学函数库为例介绍静态库的创建和使用。 要创建静态库,选择File->New菜单,弹出New对话框。选择Projects标签,在项目类型列表框中选择Win32 Static Library,在Name中输入mymath,表明要创建一个mymath.lib的静态库文件。 然后用Project->Add to Project->Files菜单往mymath工程中加入以下两个文件: 1.头文件(见清单9.1):定义了Summary和Factorial两个函数,分别用于完成求和与阶乘。注意这里使用C风格的函数,需要加入extern “C”关键字,表明它是C风格的外部函数。 清单9.1 头文件 #ifndef _MYMATH_H #define _MYMATH_H extern “C” { int Summary(int n); int Factorial(int n); } #endif 2.源文件:包含了Summary和Factorial函数的定义,见清单9.2。 清单9.2 源文件 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; }
在Build菜单下,选择Build菜单下的Build mymath.lib。Visual C++编译链接工程,在mymath\debug目录下生成mymath.lib文件。至此,静态连接库生成的工作就做完了。下面用一个小程序来测试这个静态库。
9.2.2测试静态库
用AppWizard生成一个基于对话框的应用程序test。打开test资源文件,修改IDD_TEST_DIALOG对话框资源,加入两个按钮。按钮ID和文字为: IDC_SUM “&Summary” IDC_FACTORIAL “&Factorial” 如图9-1所示。 图9-1 修改test对话框 用ClassWizard为上述两个按钮Click事件生成消息处理函数OnSum和OnFactorial,并加入代码,修改后的OnSum和OnFactorial见清单9.3。 清单9.3 OnSum和OnFactorial函数定义 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); } 由于要使用mymath.lib中的函数,首先要将mymath.lib和mymath.h两个文件拷贝到test目录下。然后用Project->Add to Project->Files命令,将mymath.lib加入到工程中。 在testdlg.cpp文件头部,还要加入头文件mymath.h: #include "stdafx.h" #include "Test.h" #include "TestDlg.h"
#include "mymath.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif 编译运行test程序,点Factorial按钮,弹出如图9-2的消息框。 图9-2 Test程序运行结果 |