There is a class with virtual functions, for example, called Parent:
Parent.h:
class Parent
{
public:
Parent() {}
virtual ~Parent();
};
Parent.cpp:
#include "Parent.h"
Parent::~Parent()
{
}
The dynamic library libParent.so is built from them.
Can I somehow create and use in my other project, for example, a class called Child:
Child.h:
#include "Parent.h"
class Child: public Parent
{
public:
Child() {}
virtual ~Child();
};
Child.cpp:
#include "Child.h"
Child::~Child()
{
}
Child tmp;
And the Child project is built using CMake, a fragment of CMakeLists.txt:
add_library (# Sets the name of the library.
parent
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file (s).
IMPORTED)
set_target_properties (parent PROPERTIES IMPORTED_LOCATION
$ ENV {PARENT_PATH} /libParent.so)
add_library (# Sets the name of the library.
child
# Sets the library as a shared library.
SHARED
# Provides a relative path to your source file (s).
$ ENV {CHILD_PATH} /Child.cpp)
target_link_libraries (# Specifies the target library.
child
parent)
As a result, when building, I get an error like this:
Child.cpp.o: Child.cpp: typeinfo for Child: error: undefined reference to 'typeinfo for Parent'
As I understand it, this happens because the virtual functions of the Parent class are defined in the Parent.cpp file and, accordingly, are located only inside the libParent.so library, and in Parent.h there is only their declaration, and as a result, when building the Child project, the compiler does not find the necessary definitions of virtual functions of the parent class and throws an error.
If I move the definition of virtual functions from Parent.cpp to Parent.h, then the error goes away. As I understand it, since now Parent.h contains complete information about the Parent class and this is enough to construct a child class Child.
But what can I do if I don't want to change this third-party library libParent.so and transfer the virtual function definitions from cpp to h, but just want to use its Parent class with virtual functions as an ancestor for my Child class? Is this possible in principle? Maybe I need to connect the libParent.so library to the Child project in some special way, so that when building the Child project, the compiler can see / use the definitions of virtual functions inside the libParent.so library?