Increase serialization using separate .h and .cpp files.

I am experimenting with expanding the serialization library, and I got most of the work. The only problem is when I try to serialize an object with separate .h and .cpp files. When I compile this command:

g++ boostSerialize.cpp Class.cpp -lboost_serialization 

I get this error:

 /tmp/cc8kbW6J.o: In function `void boost::serialization::access::serialize<boost::archive::text_oarchive, Class>(boost::archive::text_oarchive&, Class&, unsigned int)': boostSerialize.cpp:(.text._ZN5boost13serialization6access9serializeINS_7archive13text_oarchiveE5ClassEEvRT_RT0_j[void boost::serialization::access::serialize<boost::archive::text_oarchive, Class>(boost::archive::text_oarchive&, Class&, unsigned int)]+0x25): undefined reference to `void Class::serialize<boost::archive::text_oarchive>(boost::archive::text_oarchive&, unsigned int)' 

this is what is in my .h:

 #ifndef CLASS_H #define CLASS_H #include <iostream> #include <string> #include <boost/serialization/access.hpp> using namespace std; class Class{ friend class boost::serialization::access; int a,b,c; string stringy; template<class Archive> void serialize(Archive &ar, const unsigned int); public: Class(int ab, int bb, int cb); }; #endif 

and my .cpp:

 #include <iostream> #include "Class.h" using namespace std; Class::Class(int ab, int bb, int cb){ a = ab; b = bb; c = cb; stringy = "Text"; } template<class Archive> void Class::serialize(Archive &ar, const unsigned int){ ar & a & b & c & stringy; } 

Instead, I tried to place everything only in .cpp and turned it on, and it worked fine, so I know that this has something to do with including .h. For some reason, it does not find the serialization function? I think I could just use .cpp instead of both, but I really like the organization and I would like to use this for a large project. Any ideas? Thanks in advance.

+4
source share
1 answer

Your problem is not Boost.Serialization (as such), but that you are trying to separately compile the function template.

Class::serialize is a function template, which means that it is created based on the types of template parameters that are passed to is. When compiling Class.cpp compiler does not know with which types of Class::serialize the instance will be created, and therefore it will not be able to generate code.

+8
source

Source: https://habr.com/ru/post/1402553/


All Articles