Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compile C++ header-only templates to a shared library

I'm working on a code base of template classes. It's header-only (no .cpp files). I would like to hide implementation and provide a shared library plus a couple of headers containing only declaration. Unfortunately sounds like doesn't make a sense. Since there is no compiled code, so what will be in such a shared lib? Trying to remove definitions from headers after compiling, causes undefined references. Is there a way to force compiler to ship objects in dll or shared library without having to explicitly instantiate template classes?

like image 477
sorush-r Avatar asked Jul 22 '12 17:07

sorush-r


People also ask

How do I compile headers only in library?

Header-only libraries do not need to be separately compiled, packaged and installed in order to be used. All that is required is to point the compiler at the location of the headers, and then #include the header files into the application source.

Do you compile header files in C?

c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development. Such a technique basically computed the include statements and kept a cache of the flattened includes.

Can you compile a header file?

Only source files are passed to the compiler (to preprocess and compile it). Header files aren't passed to the compiler. Instead, they are included from source files.

Why can't we compile template code into its own .O file?

Because the templates are not functions, they can't be compiled separately.


2 Answers

No, there isn't and wont be a way to do that for the foreseeable future. The only way to provide template C++ code is as header files only. Modules might change that, but that is unlikely to happen before your library is finished.

Something you can try is to split into implementation and explicitly instantiate all possible use cases. Then the library you ship wont work with any other types then the instantiated ones and would significantly reduce the benefit templates bring.

like image 62
pmr Avatar answered Sep 29 '22 20:09

pmr


Template implementations need to be known at compile time. That's why you can't separate implementation from declaration. So if you want to have the advantages of templates, there is no way around passing your header(s).

like image 43
steffen Avatar answered Sep 29 '22 20:09

steffen