Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

c++ - Boost Serialization - Exporting in multiple CPP files

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

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.

Does anyone have any tips on either howto make it work with template methods, or how to export classes in multiple CPP files?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You're on the right track.

Splitting into BOOST_CLASS_EXPORT_KEY and BOOST_CLASS_EXPORT_IMPLEMENT is indeed the key to the solution.

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.

In this case, simply include BOOST_CLASS_EXPORT_IMPLEMENT in at most one (statically) linked translation unit (think: cpp file).

See for background:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...