VS2010上创建静态链接库和动态链接库

VS2010下创建静态链接库和动态链接库

下面介绍一下用VS2010如何创建静态链接库和动态链接库,并测试创建的库。

1.静态链接库

打开VS2010,新建一个项目,选择win32项目,点击确定,选择静态库这个选项,预编译头文件可选可不选。

在这个空项目中,添加一个.h文件和一个.cpp文件。名字我们起为static.h和static.cpp

static.h文件:

#ifndef LIB_H
#define LIB_H

extern "C" int sum(int a,int b);

#endif

static.cpp文件:

#include "static.h"

int sum(int a,int b)
{
	return a+b;
}
编译这个项目之后,会在debug文件夹下生成static.lib文件,这个就是我们需要的静态链接库。


下面说明如何调用静态链接库。

首先需要新建一个空项目,起名为test。将之前static项目下的static.h和static.lib这个2个文件复制到test项目的目录下,并在工程中加入static.h文件。

新建一个test.cpp文件如下:

#include <stdio.h>
#include <stdlib.h>
#include "static.h"

#pragma comment(lib,"static.lib")

int main()
{
	printf("%d\n",sum(1,2));
	system("pause");
	return 0;
}


编译运行可得结果:3

#pragma comment(lib,"static.lib"),这一句是显示的导入静态链接库。除此之外,还有其他的方法,比如通过设置路径等等,这里不做介绍。


2.动态链接库

和创建静态链接库一样,需要创建一个空的win32项目,选择dll选项。创建dynamic.cpp和dynamic.h文件

dynamic.h文件:

#ifndef DYNAMIC
#define DYNAMIC

extern "C" __declspec(dllexport)int sum(int a, int b);

#endif DYNAMIC

dynamic.cpp文件:

#include "dynamic.h"

int sum(int a, int b)
{
	return a+b;
}
编译这个项目,会在debug文件夹下生成dynamic.dll文件。

下面介绍如何调用动态链接库,这里讲的是显示的调用。

在刚才的test项目下,把static.lib和static.h文件删除,把dynamic.h和dynamic.dll复制到该目录下,并在项目中添加dynamic.h文件,修改test.cpp文件为:

#include <stdio.h>
#include <stdlib.h>
#include<Windows.h>
#include "dynamic.h"
int main()
{
	HINSTANCE hDll=NULL;
	typedef int(*PSUM)(int a,int b);
	PSUM pSum;
	hDll = LoadLibrary(L"dynamic.dll");
	pSum = (PSUM)GetProcAddress(hDll,"sum");
	printf("%d\n",pSum(1,2));
	system("pause");
	FreeLibrary(hDll);
	return 0;
}

编译运行结果为:3


特别提示:

1.extern "C"中的C是大写,不是小写

2.如果从VS2010中直接运行程序,lib和dll需要放到test项目的目录下;如果想双击项目test下的debug文件中的exe文件直接运行的话,需把lib和dll放入debug文件夹下。