打开VS2010,新建一个项目,选择win32项目,点击确定,选择静态库这个选项,预编译头文件不选。
在这个空项目中,添加一个.h文件和一个.cpp文件。名字我们起为static.h和static.cpp
static.h文件:
#ifndef LIB_H
#define LIB_H
extern "C" int sum(int a,int b);
extern "C" int substract(int a,int b);
#endif
static.cpp文件
#include "static.h"
int sum(int a,int b)
{
return a+b;
}
int substract(int a,int b)
{
return a-b;
}
编译这个项目之后(生成——》生成解决方案),会在debug文件夹下生成static.lib文件,这个就是我们需要的静态链接库。
下面说明如何调用静态链接库。
首先需要新建一个空项目,起名为test。将之前static项目下的static.h和static.lib这个2个文件复制到test项目的目录下,并在工程中加入static.h文件。
新建一个test.cpp文件如下:
#include "static.h"
#include <stdlib.h>
#include <stdio.h>
#pragma comment(lib,"static.lib")
int main()
{
printf("%d\n",sum(1,2));
printf("%d\n",substract(4,3));
system("pause");
return 0;
}
编译运行可得结果:
3
1
#pragma comment(lib,"static.lib"),这一句是显式的导入静态链接库。除此之外,还有其他的方法,比如通过设置路径等等,这里不做介绍。
或者选中工程名,点击右键->属性,在“VC++目录”的包含目录里面加入static.h的所在目录的路径,库目录里面加入static.lib所在目录的路径;在链接器->输入->附加依赖项输入“static.lib”。然后源文件里添加#include"static.h"就OK了。
题外话摘自百度百科: