我的C++应用程序存在以下问题(我刚开始使用C++)。
我相当确定它以某种方式与包含相关,但是我相信我正确地使用了包含保护,因此不确定我还能做什么。
例:
如果使用头文件中的函数主体声明以下头文件,则应用程序将按预期进行编译和运行。但是,如果我拆分为单独的.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
最佳答案
看起来您正在使用预编译的 header 。您需要在每个cpp文件中包含stdafx.h。只需在#include "stdafx.h"
之前在您的cpp中添加#include "json_ops.h"
行。
如果json_ops.h
包含在其他位置,则stdafx.h
将不会系统地包含在json_ops.cpp
文件中。
关于c++ - C++包含混淆,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23017242/