Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...