Boost Serialization - Exporting in multiple CPP fi

2019-05-31 06:06发布

问题:

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.

回答1:

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:

  • How does the compilation/linking process work?
  • What is an undefined reference/unresolved external symbol error and how do I fix it?