windows下静态库使用, 动态库的静态加载, 动态库的动态加载 原创实例!

静态库

头文件:  sumstatic.h

生成输出:  sumstatic.lib 


//sumstatic.h


#pragma once


int addInt(int a, int b);


---


//sumstatic.cpp


#include "stdafx.h"


#include "sumstatic.h"


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


----------------



动态库

头文件:  sumstatic.h

生成输出:  sumdll.lib   sumdll.dll


//sumdll.h


// 下列 ifdef 块是创建使从 DLL 导出更简单的
// 宏的标准方法。此 DLL 中的所有文件都是用命令行上定义的 SUMDLL_EXPORTS
// 符号编译的。在使用此 DLL 的
// 任何其他项目上不应定义此符号。这样,源文件中包含此文件的任何其他项目都会将
// SUMDLL_API 函数视为是从 DLL 导入的,而此 DLL 则将用此宏定义的
// 符号视为是被导出的。
#ifdef SUMDLL_EXPORTS
#define SUMDLL_API extern "C" __declspec(dllexport)
#else
#define SUMDLL_API extern "C" __declspec(dllimport)
#endif



SUMDLL_API int addInt(int a, int b);



---


//sumdll.cpp


// sumdll.cpp : 定义 DLL 应用程序的导出函数。
//


#include "stdafx.h"
#include "sumdll.h"



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



以上准备工作


------------------------


1: 静态库使用 (sumstatic.h 放到源码 include 目录下,  sumstatic.lib 放到源码 lib 目录下)


//use_sumstatic.cpp


// use_sumstatic.cpp : 定义控制台应用程序的入口点。

//


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


#include "include\\sumstatic.h"


#pragma comment(lib,"lib\\sumstatic.lib")




int _tmain(int argc, _TCHAR* argv[])
{
int _a = 3;
int _b = 5;

std::cout << "a+b = " << addInt(_a, _b) << std::endl;


system("pause");
return 0;

}


-----------


2: 动态库的静态加载 (sumdll.h 放到源码 include 目录下,  sumdll.lib 放到源码 lib 目录下, sumdll.dll 放到 生成的 exe 文件同个目录下 )


// use_sumdll_static_load.cpp : 定义控制台应用程序的入口点。
//


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


extern "C"{
#include "include\\sumdll.h"
}


#pragma comment(lib,"lib\\sumdll.lib")


int _tmain(int argc, _TCHAR* argv[])
{
int _a = 3;
int _b = 5;


std::cout << "a+b = " << addInt(_a, _b) << std::endl;


system("pause");
return 0;
}



----------------------


3: 动态库的动态加载 (只需要 sumdll.dll 放到 生成的 exe 文件同个目录下 )


// use_sumdll_dynamic_load.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <iostream>
#include <Windows.h>


int _tmain(int argc, _TCHAR* argv[])
{
typedef int (* FunPtr)(int,int); //定义函数指针


HMODULE hmd =LoadLibrary(_T("sumdll.dll"));
if(hmd){
FunPtr funPtr = (FunPtr)GetProcAddress(hmd,"addInt");
if(funPtr){
std::cout << "a+b = " << funPtr(3, 5) << std::endl;
}
FreeLibrary(hmd);
}


system("pause");

return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值