rttrorg / rttr

C++ Reflection Library
https://www.rttr.org
MIT License
3.12k stars 430 forks source link

No registration happen when class is not used in code #289

Open FlexW opened 4 years ago

FlexW commented 4 years ago

I use RTTR in my hobby game engine. My engine is a library that defines various components. I register this components with RTTR_REGISTRATION. This works fine as long as the components get somewhere instantiated in the code. If I didn't use this classes in my library and link this library to my editor executable the components get not shown up. So I guess the components get never registered. I use cmake and clang. Maybe that's not an issue with RTTR itself rather than a problem how cmake links. Any ideas what I can do to solve this problem?

LordOfTheCows commented 3 years ago

That's actually a problem with compiler optimisations. It discards that which is not used. You can force the compiler to include everything that is compiled, even that which isn't used, but that would lead to a large executable since it would probably include a lot of non-rtttr stuff.

Our workaround is to force the compiler to think that we are using the objects in the .cpp file with the registration. There are various ways to do this, but since we are also using the Cereal c++ library (https://uscilab.github.io/cereal/), we use a couple of helper macros that solve our problems (CEREAL_REGISTER_DYNAMIC_INIT in the header file, and CEREAL_FORCE_DYNAMIC_INIT in the source file that has the rttr registration). The registered class doesn't need to be used directly in the code BUT the header file must be included for this workaround to work.

See the section called "Registering from a source file" in https://uscilab.github.io/cereal/polymorphism.html for more information.

You won't have to include the library for this to work as you can be inspired by the simple definitions code that they use.