C++最基本调用动态链接库dll方法的小结

针对当时初学动态链接、静态链接,有些文档整理一下发出来算是给自己和读者一个小结。

首先创建DLL

编辑头文件

dllmain.h 头文件:

#pragma once
#if defined(_DLL_API)
#ifndef DLL_API
#define DLL_API __declspec(dllexport)
#endif
#else
#define DLL_API __declspec(dllimport)
#endif // !DLL_API
#ifndef _API
#ifdef _MSC_VER
#define _API __stdcall
#else
#define _API
#endif
#endif

//导出函数,若要导出函数,必须出现在调用约定关键字的左边(最左边)
DLL_API int add(int a, int b);

//导出类,要导出类中的所有公共数据成员和成员函数,必须出现在类名的左边(挨着)
class DLL_API cls
{
public:
	int add(int a, int b);
};

stdafx.h 头文件:

// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//

#pragma once

#include "targetver.h"

#define WIN32_LEAN_AND_MEAN             // 从 Windows 头中排除极少使用的资料
// Windows 头文件: 
#include <windows.h>

// TODO: 在此处引用程序需要的其他头文件

targetver.h 头文件:

#pragma once

// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。

// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将
// 将 _WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。

#include <SDKDDKVer.h>

编辑实现方法

dllmain.cpp:

// dllmain.cpp : 定义 DLL 应用程序的入口点。
#include "stdafx.h"
#include "dllmain.h"
//BOOL APIENTRY DllMain( HMODULE hModule,
//                       DWORD  ul_reason_for_call,
//                       LPVOID lpReserved
//                     )
//{
//    switch (ul_reason_for_call)
//    {
//    case DLL_PROCESS_ATTACH:
//    case DLL_THREAD_ATTACH:
//    case DLL_THREAD_DETACH:
//    case DLL_PROCESS_DETACH:
//        break;
//    }
//    return TRUE;
//}

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

int cls::add(int a,int b)
{
	return a + b;
}

mydll_1.cpp:

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

#include "stdafx.h"

stdafx.cpp:

// stdafx.cpp : 只包括标准包含文件的源文件
// mydll_1.pch 将作为预编译标头
// stdafx.obj 将包含预编译类型信息

#include "stdafx.h"

// TODO: 在 STDAFX.H 中引用任何所需的附加头文件,
//而不是在此文件中引用

最后检查配置

配置中“配置类型”选【动态库.dll】,理想状态点击【生成】即可生成相应dll文件。

其次调用该dll

编辑头文件

stdafx.h:

// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//

#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>

// TODO: 在此处引用程序需要的其他头文件

targetver.h:

#pragma once

// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。

// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将
// 将 _WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。

#include <SDKDDKVer.h>

编辑实现方法

mytest_1.cpp:

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

#include "stdafx.h"
#include "dllmain.h"
#include <iostream>
#include <windows.h>
int main()
{
	std::cout << add(2, 6) << std::endl;
	system("pause");
	return 0;

}

stdafx.cpp:

// stdafx.cpp : 只包括标准包含文件的源文件
// mytest_1.pch 将作为预编译标头
// stdafx.obj 将包含预编译类型信息

#include "stdafx.h"

// TODO: 在 STDAFX.H 中引用任何所需的附加头文件,
//而不是在此文件中引用

检查配置信息

要选择【应用程序.exe】,其他配置默认,顺利的话能生成对应exe可执行文件。

最后检验

将生成的动态链接库dll放入可执行文件exe的目录中,两者必须在一个目录中,双击运行exe,得结果如下:
image
如果同目录下缺少dll,则显示如下:
image

PS

很多细节可能未说明,有问题或者缺少的内容会及时更改,感谢阅读!

原文地址:https://www.cnblogs.com/sharpeye/p/15342561.html