C++ 包含混淆

标签 c++ visual-c++ mfc

我的 C++ 应用程序存在以下问题(我刚开始使用 C++)。

我相当确定它在某种程度上与 include 相关,但我相信我正确地使用了 include 守卫,所以不确定我还能做什么。

例子:

如果我在头文件中使用函数体声明以下头文件,应用程序将按预期编译和运行。 但是,如果我拆分为单独的 .h 和 .cpp 文件,构建将失败,并在本文末尾复制错误。据我所知,我想正确地将实现与 header 分开这是 a) 正确的方法和 b) 导致更快的构建。

我包含了配置属性 > 链接器 > 输入和常规 > 使用 MFC 的屏幕截图,因为在项目构建期间必须更改它以满足要求(我需要使用“在静态库中使用 MFC”) .

那么,我怎样才能正确地拆分我的文件而不让我的构建失败呢?谢谢。

json_ops.h(全部在头文件中)

#ifndef JSON_OPS_H
#define JSON_OPS_H

#include "stdafx.h"

#include "../srclib/rapidjson/document.h"

namespace cdm_data_distributable
{
    class json_ops
    {
    public:

        void test_json() const;
    };

    void json_ops::test_json() const
    {
        // json parsing example

        const char json[] = "{ \"hello\" : \"world\" }";

        rapidjson::Document d;
        d.Parse<0>(json);
    }
}

#endif

json_ops.h、json_ops.cpp(单独的文件)

头文件

#ifndef JSON_OPS_H
#define JSON_OPS_H

#include "stdafx.h"

#include "../srclib/rapidjson/document.h"

namespace cdm_data_distributable
{
    class json_ops
    {
    public:

        void test_json() const;
    };
}

#endif

.CPP文件

#include "json_ops.h"

namespace cdm_data_distributable
{
    void json_ops::test_json() const
    {
        // json parsing example

        const char json[] = "{ \"hello\" : \"world\" }";

        rapidjson::Document d;
        d.Parse<0>(json);
    }
}

产生的错误

error LNK1169: one or more multiply defined symbols found

"void * __cdecl operator new(unsigned int)" (??2@YAPAXI@Z) already defined in LIBCMTD.lib(new.obj)

"void __cdecl operator delete(void *)" (??3@YAXPAX@Z) already defined in LIBCMTD.lib(dbgdel.obj)    C:\SVN\CdmDataCds\Application\CdmDataDistributable.Ui\uafxcwd.lib(afxmem.obj)   CdmDataDistributable.Ui

enter image description here

enter image description here

最佳答案

看起来你使用的是预编译的头文件;您需要在每个 cpp 文件中包含 stdafx.h。只需在您的 cpp 中的 #include "json_ops.h" 之前添加 #include "stdafx.h" 行。

如果 json_ops.h 包含在别处,stdafx.h 将不会系统地包含到您的 json_ops.cpp 文件中。

关于C++ 包含混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23017242/

相关文章:

C++ 重写一个文件,但在一个词之前遗漏了所有内容

c++ - 内存映射文件的奇怪行为,一些观察和一些问题

c++ - 我不明白如何正确使用 set_difference

c++ - "#pragma comment"是什么意思?

c++ - 避免模​​拟 std::fstream 类的 "inheritance by dominance"警告

c++ - MFC新手: how to determine if a character is hexadecimal using "FindOneOf()"

c++ - 删除字符串中嵌入的空字符

windows - 如何使用 EnableWindow() 禁用窗口并将其灰显?

c++ - 基于对话框的 MFC 应用程序中的视觉样式?

visual-c++ - 从CStdioFile获取错误消息::Open()?