CString 是 MFC 中最常用的字串類別,功能強大且易用。但在純 SDK 或主控台專案中,預設無法直接使用。本文詳細說明在非 MFC 專案(EXE、DLL、靜態庫)中正確引入 CString 的完整步驟與注意事項。
VC 編譯器依副檔名決定編譯模式,只有 .cpp 檔包含 afx.h 才能正確啟用 MFC 支援。請確認專案中使用 CString 的檔案均為 .cpp 副檔名。
stdafx.h 中包含 <afx.h><windows.h>,務必將 <afx.h> 置於 <windows.h> 之前stdafx.h(Win32 GUI 專案修改版)#if !defined(AFX_STDAFX_H__INCLUDED_)
#define AFX_STDAFX_H__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif
#define WIN32_LEAN_AND_MEAN
#include <afx.h> // 必須在 windows.h 之前
// Windows Header Files:
#include <windows.h>
// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#ifdef _DEBUG
#pragma comment(lib, "libcmtd.lib")
#else
#pragma comment(lib, "libcmt.lib")
#endif
#endif // AFX_STDAFX_H__INCLUDED_
修改完成後,專案即可正常使用 CString 及其他核心 MFC 類別(CArray、CMap 等)。
難點在於 afx.h 內建 DllMain,會與專案自身的進入點衝突。解決方案:
專案屬性 → C/C++ → 程式碼產生 → 執行期函式庫:選擇「多執行緒偵錯 (/MTd)」或「多執行緒 (/MT)」。或在 stdafx.h 中以 #pragma comment(lib, ...) 指定。
DLLMODUL.CPP 並加入專案#include "stdafx.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define new DEBUG_NEW
/////////////////////////////////////////////////////////////////////////////
// 全域資料
// 強制連結器包含此模組給 _USRDLL
#ifdef _X86_
extern "C" { int _afxForceUSRDLL; }
#else
extern "C" { int __afxForceUSRDLL; }
#endif
stdafx.h 包含順序同 EXE 專案,確保 <afx.h> 在 <windows.h> 之前。
DLLMODUL.CPP 中的 _afxForceUSRDLL 符號會強制連結器引入 MFC 的 DLL 模組初始化代碼,替換 afx.h 中預設的 DllMain,避免重複定義錯誤。此為 MFC 官方文件推薦的「非 MFC DLL 使用 MFC 類別」標準做法。
#error Building MFC application with /MD[d] requires afx.h to be included before windows.h → 調整包含順序_DllMain@12 already defined → 確認 DLLMODUL.CPP 已加入專案且編譯非 MFC 專案使用 CString 的核心在於:正確的包含順序(afx.h 優先)+ 多執行緒執行期庫 + DLL 專案額外提供模組初始化代碼。遵循上述步驟,即可在任何 VC++ 專案中享受 CString 的便利。