首先,新建工程,选择Static Library,工程名称设为Myfunc
新建一个名为func.h的头文件,代码如下
#ifndef _define
#define _define
namespace hehe
{
int foo(int x,int y);
template <typename T>
T foo1(T x,T y);
//模板定义是不产生代码的,只有在实例化的时候才会产生代码
//所以,使用了模板的函数必须放在头文件中,因为模板需要在编译时推导
template <typename T>
T foo1(T x,T y)
{
return x+y;
}
}
#endif
再新建一个func.cpp文件,添加如下代码
#include "func.h"
namespace hehe
{
int foo(int x,int y)
{
int z=1;
for(int i=0;i<y;i++)
z*=x;
return z;
}
}
编译并建立 在debug目录里会生成一个Myfunc.lib文件,把该文件移到/Microsoft Visual Studio/VC98/Lib目录里;
把func.h移到/Microsoft Visual Studio/VC98/Include目录里、或者直接添加到工程文件中、使用#include"func.h"包含。
以上完毕后、
新建一个工程,在工程设置-->连接-->对象/库模块中增加Myfunc.lib 空格隔开
#include <iostream> #include "hello.h" using namespace std; int main(void) { cout <<hehe::foo(4,6); cout <<hehe::foo1(4,6); cout <<hehe::foo1(4.0,6.0); return 0; }
编译,运行。
成功,结束。