在非mfc程序中使用CString类
为了使用CString类,首先源文件必须是以cpp结尾的,这是因为vc默认对不同的扩展名采用不同的编译方法和错误检查,mfc的支持文件Afx.h只有由cpp为扩展名的文件包含才能够正常编译。对于exe和库要采用不同的方式。下面分别讨论:
一、在非dll或者lib的工程里,使用CString非常容易,只要两步:
1、对于没有包含<Windows.h>的stdafx.h中,只要包含了afx.h即可,而对于已经包含了<windows.h>的stdafx.h, 一定需要保证afx.h在windows.h之前被包含。另外由于默认的控制台程序采用的单线程运行库,我们要把它改成多线程库,这些工作只要在stdafx.h中进行修改就可以了(详细信息可以参考候捷的<<mfc 深入浅出>>),我使用的一个stdafx.h的例子如下(这是一个从向导生成的win32位GUI的程序的stdafx.h修改的):
这样就可以在程序中正常使用CString类了。
二、在dll或者lib的工程中,由于afx.h默认带了一个DllMain,致使要使用CString类需要几个步骤。
1、首先和控制台程序一样,如果编译环境设置了采用单线程库, 要改成多线程库,这个可以从工程属性里进行修改,详细信息可以参考候捷的<<mfc 深入浅出>>. 下面给出的是我常用的方式,可以直接把它复制到工程里使用:
2、工程目录下创建一个DLLMODUL.CPP文件,并且把它加入到当前工程中。
3、打开DLLMODUL.CPP文件,编辑这个文件为这样:
4、打开stdafx.h,把afx.h包含在windows.h前面。现在可以正常的使用CString了。
摘自:http://www.vckbase.com/document/viewdoc/?id=1437
win32控制台程序中使用CString和string
最近编一个控制台程序,开始时用字符数组,发现处理字符串很不方便.于是想到用MFC的CString类.CString的头文件是<afxwin.h>.包含头文件编译,提示错误fatal error C1189: #error : WINDOWS.H already included. MFC apps must not #include <windows.h>.后来几经周折终于找到了解决办法:
一,在工程->设置->常规选项 选择使用MFC做为静态链接库或做为共享的DLL.
二#include <afxwin.h>必须放在#include <winsock2.h>等文件的前边,具体是什么文件还没弄清楚.
所以为了方便还是把#include <afxwin.h>放在其它头文件的前边比较好.
使用string的方法是:在头文件中包含这两句#include <string>
using namespace std;