You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

rapidjson在VS2019控制台正常,MFC程序编译报错求助

问题描述

在VS2019环境下,我尝试在MFC项目中使用rapidjson,仅引入头文件并编写如下代码:

#include "rapidjson/document.h"

BOOL CMyProjectDoc::OnNewDocument()
{
    if (! CDocument::OnNewDocument())
        return FALSE;

    // TODO: add reinitialization code here
    // (SDI documents will reuse this document)

    const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
    rapidjson::Document d;
    d.Parse(json);

    return TRUE;
}

编译时出现以下错误:

\rapidjson\allocators.h(437,5): warning C4003: not enough arguments for function-like macro invocation 'max'
\rapidjson\allocators.h(437,5): error C2760: syntax error: unexpected token ')', expected 'expression'

但相同的rapidjson代码在同版本VS的控制台项目中编译正常,控制台代码如下:

#include "rapidjson/document.h"

int main()
{
    const char* json = "{\"project\":\"rapidjson\",\"stars\":10}";
    rapidjson::Document d;
    d.Parse(json);
    return 0;
}

已对比两个项目设置,确认一致,但MFC项目仍报错,请问原因是什么?

问题原因及解决办法

原因

问题出在MFC的宏定义冲突上:MFC框架的头文件里定义了一个max宏,编译MFC项目时,预处理器会把rapidjson代码中调用的std::max错误替换成这个宏,导致语法逻辑混乱,触发报错。而控制台项目没有引入MFC相关头文件,不会触发这个宏替换,所以编译正常。

解决办法

推荐用以下几种方式解决:

  • 全局禁用MFC的max/min宏:在引入rapidjson头文件之前定义NOMINMAX宏,这样MFC就不会生成max和min的宏定义,从根源避免冲突:
    #define NOMINMAX
    #include "rapidjson/document.h"
    
    BOOL CMyProjectDoc::OnNewDocument()
    {
        // 原有代码...
    }
    
  • 临时取消宏定义再恢复:如果项目其他地方需要用到MFC的max宏,可以在引入rapidjson前后做临时处理:
    #undef max
    #include "rapidjson/document.h"
    // 如果后续代码需要MFC的max宏,再重新定义回来
    #define max(a,b) (((a) > (b)) ? (a) : (b))
    
  • 修改rapidjson代码(不推荐):找到allocators.h报错的行,把std::max用括号包裹起来,避免被宏替换:
    (std::max)(value1, value2)
    
    这种方式需要修改第三方库源码,后续更新rapidjson时会丢失修改,不建议长期使用。

内容的提问来源于stack exchange,提问作者Flaviu_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:10:37