前面说了windows环境下静态库的生成和使用方法,现在来看一看windows环境下动态库的生成和使用方法。这次的代码来自《windows核心编程 第5版》中第19章“DLL基础”。
首先使用VS2008构建一个空工程,工程类型是“Win32 dynamic link library”。我们来看构建DLL模块的代码:
下面看一看如何使用这个dll文件,我们再建立一个新的空工程,工程类型为“Win32 应用程序”。在工程中添加一个文件MyExeFile1.cpp,文件中敲入如下代码:
首先使用VS2008构建一个空工程,工程类型是“Win32 dynamic link library”。我们来看构建DLL模块的代码:
/***************************************************************************
Module: MyLib.h
***************************************************************************/
#ifdef MYLIBAPI
// MYLIBAPI should be defined in all of the DLL's source
// code modules before this header file is included.
// All functions/variables are being exported.
#else
// This header file is included by an EXE source code module.
// Indicate that all functions/variables are being imported.
#define MYLIBAPI extern "C" __declspec(dllimport)
#endif
// Define any data structures and symbols here.
// Define exported variables here. (NOTE: Avoid exporting variables.)
MYLIBAPI int g_nResult;
// Define exported function prototypes here.
MYLIBAPI int Add(int nLeft, int nRight);
// End of File /
/***************************************************************************
Module: MyLibFile1.cpp
***************************************************************************/
// Include the standard Windows and C-Runtime header files here.
#include <windows.h>
// This DLL source code file exports functions and variables.
#define MYLIBAPI extern "C" __declspec(dllexport)
// Include the exported data structures, symbols, functions, and variables.
#include "MyLib.h"
// Place the code for this DLL source code file here.
int g_nResult;
int Add(int nLeft, int nRight) {
g_nResult = nLeft + nRight;
return(g_nResult);
}
// End of File /
对程序进行编译链接,会生成一个名为MyDll.dll的动态链接库文件。下面看一看如何使用这个dll文件,我们再建立一个新的空工程,工程类型为“Win32 应用程序”。在工程中添加一个文件MyExeFile1.cpp,文件中敲入如下代码:
/***************************************************************************
Module: MyExeFile1.cpp
***************************************************************************/
// Include the standard Windows and C-Runtime header files here.
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#include <stdlib.h>
// Include the exported data structures, symbols, functions, and variables.
#include "MyLib\MyLib.h"
#pragma comment(lib,"Mydll.lib")
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) {
int nLeft = 10, nRight = 25;
TCHAR sz[100];
StringCchPrintf(sz, _countof(sz), TEXT("%d + %d = %d"),
nLeft, nRight, Add(nLeft, nRight));
MessageBox(NULL, sz, TEXT("Calculation"), MB_OK);
StringCchPrintf(sz, _countof(sz),
TEXT("The result from the last Add is: %d"), g_nResult);
MessageBox(NULL, sz, TEXT("Last Result"), MB_OK);
return(0);
}
// End of File /
记得要将MyLib.h和Mydll.lib文件放到当前工程的目录下,否则会编译链接失败。这个Mydll.lib是生成dll文件的时候生成的。需要注意的一点是:我们编译和链接的时候并不需要MyDll.dll文件,只有在程序运行的时候才需要它。这一点儿和linux环境中是不同的。