模块化程序设计,经常用到动态库dll和静态库lib,下面就这两种的方式进行比较:
一、动态库 DLL
1、创建DLL工程:flie-new-projects-visual c++(win32)-win32 console application,application setting-application type选择DLL
2、为新建的工程添加代码:
a、源文件:dll.cpp
#include "dll.h"
int Add(int a,int b)
{
return a+b;
}
b、 头文件:dll.h
int _declspec(dllexport) Add(int a,int b);
3、编译之后生成两个有用的文件:dll.lib和dll.dll
4、调用动态库 DLL
a、隐式链接:
#include <iostream>
using namespace std;
int _declspec(dllimport) Add(int a,int b);//dll需要放在main程序的debug下面
#pragma comment(lib,"dll.lib"); //指定lib的目录,lib最好与dll一起放在debug下面,也可以在project property-linker-input里面添加dll.lib;路径用\\或者/
int main()
{
int a;
int b;
int sum;
cout<<"please input two number:"<<endl;
cin>>a>>b;
sum=Add(a,b);
cout<<"a+b="<<sum<<endl;
return 0;
}
b、显式加载:
#include <windows.h>
#include <string>
#include <iostream>
using namespace std;
int main()
{
HINSTANCE hDll;
int a;
int b;
int sum;
int error;
hDll=LoadLibrary("dll.dll");
if(hDll==NULL)
{
error=GetLastError();
printf("error1=%d\n",error);
FreeLibrary(hDll);
return -1;
}
typedef int (* FUNC)(int a,int b);
FUNC Add=(FUNC)GetProcAddress(hDll,"Add");
if(!Add)
{
error=GetLastError();
printf("error2=%d\n",error);
FreeLibrary(hDll);
return -1;
}
cout<<"please input two number:"<<endl;
cin>>a>>b;
sum=Add(a,b);
cout<<"a+b="<<sum<<endl;
return 0;
}
二、静态库
1、创建LIB工程:flie-new-projects-visual c++(win32)-win32 console application,application setting-application type选择static lib
2、为新建的工程添加代码:
a、源文件:dll.cpp
#include "dll.h"
int Add(int a,int b)
{
return a+b;
}
b、 头文件:dll.h
int _declspec(dllexport) Add(int a,int b);
3、编译之后生成1个有用的文件:dll.lib,另外供别的模块调用需要头文件dll.h
4、调用静态库 LIB
#include <iostream>
using namespace std;
#include "DLL.h" //需要头文件
#pragma comment(lib,"dll.lib"); //指定lib的目录,lib最好放在debug下面,也可以在project property-linker-input里面添加dll.lib;路径用\\或者/
int main()
{
int a;
int b;
int sum;
cout<<"please input two number:"<<endl;
cin>>a>>b;
sum=Add(a,b);
cout<<"a+b="<<sum<<endl;
return 0;
}