0

I am trying to compile a .so for a fairly large project, and I am running into the issue that none of the classes, templated or otherwise, written in any of the files are in the completed .so file.

I made the file with:

g++ -shared -fPIC -Wall filename1.cpp -o libfilename1.so

I'll spare you the full output of the nm, but all of the non-templated functions that were defined are there, and none of the templated functions, templated classes, or classes are there. I tried using __attribute__ ((visibility=("default"))) in the class declarations, but it didn't seem to do anything.

  • Probably because templates are *templates* and not concrete classes. Take e.g. `std::vector`, it is a template. `std::vector` is a concrete class. – Some programmer dude Mar 15 '17 at 17:08
  • Templates must be instantiated in order to be compiled. The conclusion is that you can't have templates in your shared library. – DeiDei Mar 15 '17 at 17:10
  • Does your .so instantiate some of exported template functions? – em2er Mar 15 '17 at 17:10
  • 4
    There's no such thing as a "templated class". That's may be at the core of the misunderstanding. There are only "classes" and "class templates". Templates are not classes. (Also, even classes don't get emitted to object code as such, only functions and static data members do.) – Kerrek SB Mar 15 '17 at 17:11

1 Answers1

0

A template is something that exists for the compiler during compilation only. The complier uses the template to create instantiations of said template. Those are then "real" classes or functions. They're visible to the linker and can thus be put into a shared library.

To achieve that you need to inform the compiler that is compiling the code which links against the library that a particular instantiation of some template exists within the library. This is done by declaring an explicit instantiation (in the header):

extern template​ Class<int>; // since C++11

Second you need to inform the compiler which compiles the code for the library that said instantiation shall exist, using an explicit template definition (in the source code of the library):

template Class<int>;
Daniel Jour
  • 15,896
  • 2
  • 36
  • 63