简体   繁体   中英

C++ Include Confusion

I have the following issue with my C++ application (I'm just starting out with C++).

I'm fairly sure that it relates to includes in some way, but I believe I am correctly using include guards, so not sure what else I can do.

Example:

If I declare the following header file with the function body in the header file, the application compiles and runs as expected. If I split out into separate .h and .cpp files however, the build fails with the error copied at the end of this post. I'd like to correctly separate the implementation from the header as I understand this is a) the correct way to do it and b) results in faster builds.

I have included screenshots for the Configuration Properties > Linker > Input and the General > Use of MFC as this have had to be changed during the project build to satisfy requirements (I need to use "Use MFC in a Static Library").

So, how can I split my files out properly and not have my build fail? Thanks.

json_ops.h (all in header file)

#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 (separate files)

Header file

#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 File

#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);
    }
}

Resulting Errors

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

在此处输入图片说明

在此处输入图片说明

It looks like you are using pre-compiled headers; you need to include the stdafx.h in every cpp file. Simply add the #include "stdafx.h" line in your cpp, before #include "json_ops.h" .

If json_ops.h is included elsewhere, stdafx.h won't be included systematically to your json_ops.cpp file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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