制作自己的静态库

一 生成lib文件

使用vs2019创建工程的时候选择静态库
image

这里我们做一个简单加减乘除的库文件

// ------------------------   TestLib1.h  ----------------------------
#pragma once
#ifndef _TESTLIB_H_
#define _TESTLIB_H_

int testAdd(int a, int b);
int testSub(int a, int b);
int testMul(int a, int b);
int testDiv(int a, int b);

#endif // !_TESTLIB_H_


// ---------------------------   TestLib1.cpp   ------------------------
#include "pch.h"
#include "framework.h"
#include "TestLib1.h"

int testAdd(int a,int b)
{
    return  a + b;
}

int testSub(int a, int b)
{
    return  a - b;
}

int testMul(int a, int b)
{
    return a * b;
}

int testDiv(int a, int b)
{
    return a / b;
}


点击生成解决方案,这里就生成了一个lib文件
image

二 测试

新建一个空项目testLib,把TestLib1.h文件和TeseLib1.lib文件拷贝过来放到同目录下,在空项目中添加现有项TestLib1.h
image
在项目--属性--连接器--输入--附加依赖项中添加TestLib1.lib
image

#include <iostream>
#include "TestLib1.h"

using namespace std;
// 测试代码
int main()
{
    cout << "5 + 3 = " << testAdd(5, 3) << endl;
    cout << "5 - 3 = " << testSub(5, 3) << endl;
    cout << "5 * 3 = " << testMul(5, 3) << endl;
    cout << "5 / 3 = " << testDiv(5, 3) << endl;

    return 0;
}

image

posted @ 2022-04-12 12:52  荒年、  阅读(51)  评论(0编辑  收藏  举报