針對當時初學動態鏈接、靜態鏈接,有些文檔整理一下發出來算是給自己和讀者一個小結。
首先創建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,得結果如下:

如果同目錄下缺少dll,則顯示如下:

PS
很多細節可能未說明,有問題或者缺少的內容會及時更改,感謝閱讀!
