Boost Serialization - 以多个 CPP 文件导出
最近几天我一直在努力解决 Boost 序列化问题:
The last days I have been struggeling with a Boost Serialization problem:
我正在尝试对多个文件中的多个派生类进行序列化和反序列化.为了保持通用性,我创建了模板函数,例如:
I am trying to serialize and deserialize multiple derived classes in multiple files. In order to keep it generic I have created template functions like:
template<typename T>
void
Helper::SaveToFile(T* data, std::string file)
{
std::ofstream ofs(file.c_str());
boost::archive::text_oarchive oa(ofs);
oa << data;
}
为了使派生类的序列化工作,我需要使用 Boost 宏 BOOST_CLASS_EXPORT
.但是,我不能将此模板方法放在 CPP 文件中,并且在标题中使用宏时,我会收到这些烦人的duplicate init_guid
"错误.
For serialization of derived classes to work, I need to use the Boost macro BOOST_CLASS_EXPORT
. However, I cannot place this template method in a CPP file and with the macro in the header I get these annoying "duplicate init_guid
" errors.
即使我选择不使用模板方法,我仍然会收到这些错误,因为我在不同的文件中有不同的序列化方法,因此会导出多次.
And even if I choose not to use a template method, I still get these errors due to the fact, that I have different serialize methods in different files and therefore exporting multiple times.
是否有人对如何使其与模板方法一起使用或如何在多个 CPP 文件中导出类有任何提示?
Does anyone have any tips on either howto make it work with template methods, or how to export classes in multiple CPP files?
我已经尝试将 BOOST_CLASS_EXPORT
拆分为 BOOST_CLASS_EXPORT_KEY
和 BOOST_CLASS_EXPORT_IMPLEMENT
,仍然导致同样的错误.另外,当只有特定类的头文件时,我真的不知道将 BOOST_CLASS_EXPORT_IMPLEMENT
宏放在哪里.
I have already tried splitting BOOST_CLASS_EXPORT
into BOOST_CLASS_EXPORT_KEY
and BOOST_CLASS_EXPORT_IMPLEMENT
, still leading to the same error. Also, I didnt really know where to put the BOOST_CLASS_EXPORT_IMPLEMENT
macro when there is only a Header file for a specific class.
推荐答案
你在正确的轨道上.
拆分成BOOST_CLASS_EXPORT_KEY
和BOOST_CLASS_EXPORT_IMPLEMENT
确实是解决问题的关键.
Splitting into BOOST_CLASS_EXPORT_KEY
and BOOST_CLASS_EXPORT_IMPLEMENT
is indeed the key to the solution.
与所有具有外部链接的 C++ 符号一样,您
As with all C++ symbols with external linkage, you
- 可以将声明放在某个共享位置(如头文件)
- 必须将定义放在单个翻译单元中,以便只有一个链接器输入包含定义.
- can put declarations in some shared location (like the header file)
- must put definitions in a single translation unit, so that only one linker input contains a definition.
在这种情况下,只需将 BOOST_CLASS_EXPORT_IMPLEMENT
包含在最多一个(静态)链接的翻译单元中(想想:cpp 文件).
In this case, simply include BOOST_CLASS_EXPORT_IMPLEMENT
in at most one (statically) linked translation unit (think: cpp file).
查看背景:
- 编译/链接过程如何工作?一个>
- 什么是未定义的引用/未解决的外部符号错误,我该如何解决?
相关文章