简体   繁体   中英

C++ shared libraries with inheritance

I have a library (a.so) with a base classes (MyClassA). Another library (b.so) has a class MyClassB that inherits from MyClassA (in a.so). I compile MyClassA.h and MyClassA.cpp isolated in a.so. MyClassB.h and MyClassB.cpp are compiled in isolation (with a reference to MyClassA.h but without adding MyClassA.h to b.so). I then link b.so to a.so.

To summarize:

  1. a.so contains MyClassA.h and MyClassA.cpp
  2. b.so contains MyClassB.h and MyClassB.cpp
  3. b.so is linked to a.so

When I try to compile, I get a number of reference errors to MyClassA, caused by b.so.

When I compile b.so and add MyClass.h to it, the library compiles and runs without any errors. Hence:

  1. a.so contains MyClassA.h and MyClassA.cpp
  2. b.so contains MyClassB.h, MyClassB.cpp AND MyClassA.h
  3. b.so is linked to a.so

Is it possible in C++ to use my first option, or is it required to always include the base headers in subclass library?

If you derive ClassB from ClassA you should have your ClassA defined , when deriving, not only declared ( referenced ). That is why you have to include ClassA header file.

But if you implemented ClassA functions in cpp file, not in header, actual code of ClassA will be in a.so , so, includeing ClassA header file is not really a problem.

如果class B是从class A派生class A ,则必须包括class A头文件。

All derived classes must #include base class declarations in compilation time. Base class implementation must be known in linking time.

In your case:

  1. a.so contains MyClassA.h and MyClassA.cpp
  2. b.so contains MyClassB.h and MyClassB.cpp but MyClassB.h `#include "MyClassA.h"
  3. b.so links a.so using:

g++ -o b.so -la

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM