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

来源:互联网 发布:投稿系统php源码 编辑:程序博客网 时间:2024/05/17 22:51

静态库

头文件:  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;
}


0 0
原创粉丝点击