c++clangshared-libraries

Exported typeinfo for pure virtual class in a shared library


I created a test case here:

https://github.com/KapitanPL/inside_cast_example

Using clang I want to compile an executable and a lib. The lib contains complex hierarchy of classes. Most of them virtual.

I want to be able to cast a to a virtual class.

However this seems impossible as typeinfo of virtual class is a weak exported symbol and dynamic_cast in the executable fails.

The mentioned repository creates "inside_cast" that delegates the cast to the lib. However this is quite cumbersome.

Is there a way how to use dynamic_cast in the executable to cast to virtual class?


Solution

  • If the class can be generated from the header file then each library will create its own virtual table and RTTI data, instead move one virtual function to the .cpp file so no other library can create this Table, and the linker will have to grab it from the original library.

    // .hpp file
    
    class DLLEXPORT B: virtual public A {
    public:
       virtual ~B(); 
       virtual QString getName() = 0;
    };
    
    // .cpp file
    B::~B() = default;
    

    yes, this prevents inlining, and every use has to go back to the original library. we just prevented every other library from creating its own copy.