2

Say that I am making a shared library and have set:

set(CMAKE_CXX_VISIBILITY_PRESET hidden)

So that I must manually export the public API. Now say that I have a templated class that is split into 2 files: a my_lib.hpp which contains just the declaration:

template <typename Scalar>
class MyLibClass { ... };

and a my_lib.cpp which contains the implementation and explicit instantiation:

...
template class MyLibClass<float>;
template class MyLibClass<double>;

I then use CMake's generate_export_header() to generate a my_lib_export.hpp file which contains the appropriate export declarations. Which file should I include it into? In the header it would be:

#include "my_lib_export.hpp"
class MY_LIB_EXPORT MyLibCass { ... };

While in the implementation file, it would be:

#include "my_lib_export.hpp"
...
template class MY_LIB_EXPORT MyLibClass<float>;
template class MY_LIB_EXPORT MyLibClass<double>;

In my very simple example, both compile and link without issue. But I'm wondering, is there a difference between the two? Do they serve different purposes, or are they completely interchangeable?

starball
  • 20,030
  • 7
  • 43
  • 238
Chris Gnam
  • 311
  • 2
  • 7
  • @revision#1: what cpp? Doesn't the explicit instantiation need to be available at compile time? If the explicit instantiated template is part of the public interface of the library, shouldn't there be no "cpp" file for it (and everything go in the header)? – starball Feb 14 '23 at 03:04
  • I'm a bit confused by your question because, as far as I'm aware (and as described in [this SO answer](https://stackoverflow.com/a/5864438/8304579) an explicit instantiation of a template **must** go in the implementation file, and not the header. – Chris Gnam Feb 14 '23 at 03:07
  • 1
    @user not always. IF you have a template, because implementation details are repeated, but you only want the template to be available for a set of types, you can hide the template implementation and force generation for those types. See https://stackoverflow.com/a/2155790/1294207 – Fantastic Mr Fox Feb 14 '23 at 03:08
  • headers are source files too. – starball Feb 14 '23 at 03:08
  • @FantasticMrFox whoops. completely forgot about that. I even do that in a project of my own :P – starball Feb 14 '23 at 03:12

0 Answers0