在WIN32 DLL中使用MFC

最近用WIN32 DLL,为了方便要用到MFC的一些库,又不想转工程,就网上找了很多方法,发现没有详细的介绍,有的也行不通,现在成功在WIN32 DLL中使用了MFC,记录一下以防以后用到忘记

一、修改预编译头文件(stdafx.h)

在stdafx.h文件中添加下面代码,包含一些MFC的头文件,这些可以在一个MFC工程中复制过来

 1 #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS    // 某些 CString 构造函数将为显式的
 2 
 3 #include <afxwin.h>         // MFC 核心组件和标准组件
 4 #include <afxext.h>         // MFC 扩展
 5 
 6 #ifndef _AFX_NO_OLE_SUPPORT
 7 #include <afxole.h>         // MFC OLE 类
 8 #include <afxodlgs.h>       // MFC OLE 对话框类
 9 #include <afxdisp.h>        // MFC 自动化类
10 #endif // _AFX_NO_OLE_SUPPORT
11 
12 #ifndef _AFX_NO_DB_SUPPORT
13 #include <afxdb.h>            // MFC ODBC 数据库类
14 #endif // _AFX_NO_DB_SUPPORT
15 
16 #ifndef _AFX_NO_DAO_SUPPORT
17 #include <afxdao.h>            // MFC DAO 数据库类
18 #endif // _AFX_NO_DAO_SUPPORT
19 
20 #include <afxdtctl.h>        // MFC 对 Internet Explorer 4 公共控件的支持
21 #ifndef _AFX_NO_AFXCMN_SUPPORT
22 #include <afxcmn.h>            // MFC 对 Windows 公共控件的支持
23 #endif // _AFX_NO_AFXCMN_SUPPORT

二、修改编译配置

我使有的是VS2003

1、项目->属性->常规->MFC的使用->在静态库中使用MFC(动态或静态都可以)

2、链接器->输入->

    因为编译的时候会因为链接的顺序问题导致链接错误,所以这里要改两个LIB的链接顺序

    先在‘忽略指定库中’忽略掉这两个DLL,分别是uafxcw.lib和libcpmt.lib,如果是DEBUG工程,还需要填入libcmt.lib

    再在'附加依赖项'中以uafxcw.lib libcpmt.lib的顺序填入

 三、在你的主文件中加入代码

在最前面加入

 1 #ifdef _DEBUG
 2 #undef THIS_FILE
 3 static char THIS_FILE[] = __FILE__;
 4 #endif
 5 
 6 #define new DEBUG_NEW
 7 
 8 /////////////////////////////////////////////////////////////////////////////
 9 // global data
10 
11 // The following symbol used to force inclusion of this module for _USRDLL
12 #ifdef _X86_
13 extern "C" { int _afxForceUSRDLL; }
14 #else
15 extern "C" { int __afxForceUSRDLL; }
16 #endif

这样不用从CWinApp中派生一个类再外部定义来使用MFC的入口点,可以直接使用原来的写好的DllMain入口点

 只是在链接那一块还是出了几个错误,
error LNK2005: "private: __thiscall type_info::type_info。。。

最后用的:
附加依赖项:msvcrtd.lib LIBCMTD.lib
忽略特定库:LIBCMTD.lib;msvcrtd.lib

编译通过了,MFC的类编译器也认识了

posted @ 2015-06-19 21:35  银河彼岸  阅读(273)  评论(0编辑  收藏  举报