Source.def
LIBRARY exportDll2
EXPORTS
Add
exportDll2.h
// The following ifdef block is the standard way of creating macros which make exporting // from a DLL simpler. All files within this DLL are compiled with the EXPORTDLL2_EXPORTS // symbol defined on the command line. This symbol should not be defined on any project // that uses this DLL. This way any other project whose source files include this file see // EXPORTDLL2_API functions as being imported from a DLL, whereas this DLL sees symbols // defined with this macro as being exported. #ifdef EXPORTDLL2_EXPORTS #define EXPORTDLL2_API __declspec(dllexport) #else #define EXPORTDLL2_API __declspec(dllimport) #endif //EXPORTDLL2_API int fnexportDll2(void); int Add(int a, int b);
exportDll2.cpp
// exportDll2.cpp : Defines the exported functions for the DLL. // #include "pch.h" #include "framework.h" #include "exportDll2.h" // This is an example of an exported function. //EXPORTDLL2_API int fnexportDll2(void) //{ // return 0; //} int Add(int a, int b) { return a+b; }
main.cpp
#include<stdio.h> #include<windows.h> //注意dll文件名和后缀名不区分大小写 typedef int (*FUNC)(int a, int b); //引用库的时候必须包含两个文件 //#include"../exportDll2/exportDll2.h"//1.引用头文件 //#pragma comment(dll,"../Debug/EXPORTDLL2.dll")//2.引用库文件 int main() { HINSTANCE hDll = ::LoadLibrary("eXPORTDLL2.dll"); { int result; // 取得Add()函数的地址 //FUNC mAdd = (FUNC)::GetProcAddress(hDll, "?Add@@YAHHH@Z"); FUNC mAdd = (FUNC)::GetProcAddress(hDll, "Add"); if (mAdd != NULL) { result = mAdd(1, 2); printf("%d", result); } else printf("Error"); // 卸载DLL库 ::FreeLibrary(hDll); } /*int result; result = Add(1, 2); printf("%d", result);*/ return 0; }
注:dll如果以c++方式导出,用的时候以c使用,编译器对函数的修饰不一样,就会出错,提示无法解析外部符号
将exportDll.h改为
#ifdef EXPORTDLL2_EXPORTS #define EXPORTDLL2_API __declspec(dllexport) #else #define EXPORTDLL2_API __declspec(dllimport) #endif #ifdef __cplusplus extern "C" { #endif //EXPORTDLL2_API int fnexportDll2(void); int Add(int a, int b); #ifdef __cplusplus } #endif