静态库&动态库创建

博客介绍了静态库lib和动态库dll的相关知识。生成解决方案会生成lib,其最终嵌入在.exe文件中,其他工程包含lib就能调用函数。对于动态库dll,介绍了函数导出和导入的声明方式,还提及在工程属性中定义DLLAPI,以及隐式和显式调用dll的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.静态库lib

生成解决方案会生成lib,最终lib文件嵌入在.exe文件中. 在其他工程中包含lib就能调用静态库中的函数

test
  

#include
#include
#include"../testlib/textlib.h"
#pragma comment(lib, "testlib.lib")//会将所有的静态库文件嵌入到exe文件中,包含的lib越多,exe文件越大
                        //动态库dll不用嵌入exe,所以exe不会很大
int main()
 {
    printf("请输入两个整数\n");
    int a, b;
    scanf("%d%d", &a, &b);
    
//调用静态库
    printf("a+b=%d\n",add(a, b));
    printf("a-b=%d\n", sub(a, b));
    system("pause");
    return 0;
}

2.动态库dll

在头文件中声明函数之前加__declspec(dllexport),eg:

testdll.h

#ifndef __DLL
#define __DLL

#ifdef DLLAPI
    #define DLLAPI __declspec(dllexport)
#else
    #define DLLAPI __declspec(dllimport)

#endif // DLLAPI


extern "C" DLLAPI int add(int a, int b);  //使用extern "C"表面使用C语言的方式导出函数,
                                  //否则用C++的方式导出,会导致函数名发生改变
extern "C" DLLAPI int sub(int a, int b);


#endif // !__DLL

其中__declspec(dllexport)用来申明导出add和sub函数,供其他工程调用dll时可以用add和sub两个函数,而当其他工程项目中调用add和sub时,再用DLLAPI申明时,表示的是__declspec(dllimport),即从动态库中导入add和sub函数。
在testdll工程属性-->C/C++-->预处理器-->预处理器定义中定义DLLAPI。
这样一来在其他工程中没有定义DLLAPI

隐式调用dll

在其他工程中隐式调用dll

另一个工程下的test.cpp

#include
#include 
#include
#include "stdafx.h"
#include "../testdll/testdll.h"
#pragma comment (lib,"testdll.lib")//隐式调用动态库

int main()
{
    int a, b;
    printf("请输入两个整数:");
    scanf_s("%d%d", &a, &b);

    printf("a+b=%d", add(a, b));
    printf("a-b=%d", sub(a, b));
    system("pause");
    
    return 0;
}

显式调用dll

显示调用test.cpp

#include "stdafx.h"//头文件的添加有先后
#include
#include 
#include  //包含了HMODULE
#include

#include "../testdll/testdll.h"
//#include
//#pragma comment (lib,"testdll.lib")//隐式调用动态库

typedef int(*PADD)(int a, int b);
typedef int(*PSUB)(int a, int b);

int main()
{
    //加载dll文件
    HMODULE hdll = LoadLibrary(L"../x64/Debug/testdll.dll");
    if (hdll == NULL)
    {
        printf("cannot load testdll.dll");
        return 0;
    }
    

    int a, b;
    printf("请输入两个整数:");
    scanf_s("%d%d", &a, &b);

    PADD padd = (PADD)GetProcAddress(hdll, "add");
    PSUB psub = (PSUB)GetProcAddress(hdll, "sub");
    printf("a+b=%d", padd(a, b));
    printf("a-b=%d", psub(a, b));
    
    
    FreeLibrary(hdll);
    system("pause");
    return 0;
}

转载于:https://www.cnblogs.com/elong1995/p/10956785.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值