繁体   English   中英

C ++包含混淆

[英]C++ Include Confusion

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

我相当确定它以某种方式与包含相关,但是我相信我正确地使用了包含保护,因此不确定我还能做什么。

例:

如果我在头文件中声明带有函数主体的以下头文件,则应用程序将按预期编译并运行。 但是,如果我拆分为单独的.h和.cpp文件,则构建将失败,并在此文章结尾处复制错误。 我想正确地将实现与标头分开,因为我知道这是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

在此处输入图片说明

在此处输入图片说明

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

如果json_ops.h包含在其他位置,则stdafx.h将不会系统地包含在您的json_ops.cpp文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM