Home > Mobile >  Limit inheritance of classes to specific library in C
Limit inheritance of classes to specific library in C

Time:01-21

I am trying to limit the inheritance of an c class to within the same library, while allowing it to be instantiated in other libraries.

The use case is that I have some code that needs to be real-time capable (compiled with special flags and poisoned code) and that needs to be used/interfaced to non-RT code. However, I need to make absolutely sure that no non-RT code can ever be called inside the RT code. Therefore I have to libraries: one that is RT capable and one that isn't (which depends on the RT library and may use code from it).

Now, I have some abstract classes, which I want to be only inherited from inside of the RT library. Is it possible to prohibit the inheritance of those ABCs from classes defined outside of the RT library?

What I came up so far (without it working) is defining a macro that makes the classes final outside of RT code and a templated base class that uses std::conditional

class BaseA REALTIME_FINAL
{
    virtual void foo() = 0; 
}

template <bool allow = REALTIME_TRUE>
class BaseB : : virtual public std::conditional<allow, std::true_t, std::nullptr_t>::type
{
    virtual void foo() = 0; 
}

While both of these methods prohibit the inheritance from the abstract base, it also makes it impossible in the non-RT library to call or instantiate (or even include the header) any classes derived from it in the RT lib.

CodePudding user response:

You can solve this problem much more simply, by moving your realtime code into its own library with its own header files, and building it without any dependency on your non-realtime library.

Put your realtime and non-realtime headers into separate directories, and if your realtime code is built as a shared library, use the linker option to prohibit undefined symbols in that library.

Then all you have to do is remember not to add your system's equivalent of -Inon-realtime or -lnon-realtime in the realtime library's build configuration.

CodePudding user response:

One thing you need to think hard is - you can solve this problem today but tomorrow an intern makes changes that sneak into your code which compiles but will break in the hands of your client. So I am quite dramatic on adopting a solution that does not leave anything to imagination.

My go-to approach is always to separate libraries with a C API. This guarantees that no C features, which compilers are frequently guilty of manipulating, can be tampered.

More often I use this to encapsulate code that was compiled with the old ABI (pre-C 11) which is unfortunately still common from certain vendors.

This also guarantees that I can access these features from a CD/CI perspective from other scripting languages like Python, Java, Rust more easily.

  • Related