Boost logo

Boost :

Subject: [boost] [serialization] duplicate symbols when trying to BOOST_CLASS_EXPORT
From: V D (zedxz2_at_[hidden])
Date: 2011-12-02 00:11:58


Hi,

I'm using boost serialization to serialize a bunch of classes, sometimes I need to serialize via a base pointer to a derived class.
Let's consider the very simple case where we have a class B deriving from class A.

/*** a.h ***/
#ifndef __A__H
#define __A__H
#include <iostream>

class A
{
private:
  virtual void make_polymorphic() = 0;
 
  friend class boost::serialization::access;
  template <typename Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    std::cout << "A!\n";
  }
};
#endif
 

/*** b.h ***/
#ifndef __B__H
#define __B__H
 
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>
#include "a.h"
 
class B : public A
{
private:
  friend class boost::serialization::access;
  template <typename Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    ar & boost::serialization::base_object<A>(*this);
    std::cout << "B!\n";
  }
 
  virtual void make_polymorphic() {}
};
 
BOOST_CLASS_EXPORT(B);
 
#endif
 

I'm using the BOOST_CLASS_EXPORT so that it registers a GUID for class B, so that serialization of a base pointer to a derived class works.
This works fine.

My problem is that, if I have 2 files that include b.h, I will get duplicate symbols for B's guid.

For example, suppose we add b.cpp with an empty default constructor, just so that we compile another file.

#include "b.h"

B::B()
{
}

Let's use the following main:

// main.cpp
#include <iostream>
#include <fstream>
#include <boost/archive/binary_oarchive.hpp>
#include "b.h"
 
int main()
{
  std::ofstream of("mybin.bin");
  boost::archive::binary_oarchive oa(of);
 
  A* b = new B();
  oa << b;
 
 return 0;
}

Which I compile with g++ main.cpp b.cpp -lboost_system -lboost_serialization -o main
I get, ld: duplicate symbol boost::archive::detail::extra_detail::init_guid<B>::g

If I don't have 2 files, then of course I don't have duplicate symbols and the serialization of the polymorphic object works fine.

Any idea how to resolve this issue?

Thank you
-V


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk