首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

在非 MFC 程式中使用 CString 完整指南:控制台與 DLL 專案配置

     編輯:VC 教學

前置條件

  • 源文件副檔名必須為 .cpp,VC 預設僅對 .cpp 啟用 MFC 支援。
  • 需在 stdafx.h 中正確包含 <afx.h> 並調整運行時庫為多執行緒版本。

一、控制台/EXE 專案(非 DLL/LIB)

修改 stdafx.h,確保 afx.h 在 windows.h 之前包含:

// stdafx.h
#if !defined(AFX_STDAFX_H__...)
#define AFX_STDAFX_H__...

#if _MSC_VER > 1000
#pragma once
#endif

#define WIN32_LEAN_AND_MEAN

#include <afx.h> // 必須在 windows.h 之前

#include <windows.h>
// C Runtime Headers
#include <stdlib.h> <malloc.h> <memory.h> <tchar.h>

#ifdef _DEBUG
#pragma comment(lib, "libcmtd.lib")
#else
#pragma comment(lib, "libcmt.lib")
#endif
#endif

即可在程式中正常使用 CString。

二、DLL/LIB 專案

afx.h 預設帶 DllMain,需額外步驟:

  1. 同樣將運行時庫設為多執行緒(專案屬性或 #pragma comment(lib,...))。
  2. 專案目錄建立 DLLMODUL.CPP 並加入專案,內容:
#include "stdafx.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define new DEBUG_NEW

// global data
#ifdef _X86_
extern "C" { int _afxForceUSRDLL; }
#else
extern "C" { int __afxForceUSRDLL; }
#endif
  1. stdafx.h 中同樣將 afx.h 置於 windows.h 前。

完成後即可在 DLL 中使用 CString。

關鍵點總結

  • 包含順序:afx.h → windows.h
  • 運行時庫:多執行緒偵錯 libcmtd.lib / 發布 libcmt.lib
  • DLL 專案需 DLLMODUL.CPP 強制連結 MFC 狀態
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved