我的 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
最佳答案
看起来你使用的是预编译的头文件;您需要在每个 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/