I have defined an interface using C++ abstract class. I want to instantiate it multiple times for different variants of my project (variants can be hardware variants or OS variants). My goal is to create shared libraries for each variant and use the right one for a given project without having to re-compile anything.
I order to retrieve the required instance for a given variant, I am using a public function. In the cpp file of each variant I am defining a function to return the instance for that variant. In the main code I am making an extern declaration of this function. I intend to call a method of the interface using the returned object.
// Interface.hpp
class Interface {
public:
virtual void routine() = 0;
};
// variantA.cpp
class variantA : public Interface {
public:
void routine() {
printf( "We are in variantA\n" );
}
} variant;
Interface& getVariant() {
return variant;
}
// variantB.cpp
class variantB : public Interface {
public:
void routine() {
printf( "We are in variantB\n" );
}
} variant;
Interface& getVariant() {
return variant;
}
// main.cpp
#include "Interface.hpp"
extern Interface& getVariant();
int main() {
Interface& interface = getVariant();
interface.routine();
}
// build.sh
g++ -c -fPIC -O0 variantA.cpp
g++ -c -fPIC -O0 variantB.cpp
g++ variantA.o -shared -o libvariantA.so
g++ variantB.o -shared -o libvariantB.so
ln -s libvariantA.so libvariant.so
g++ -L. -lvariant main.cpp -o main
Main question: Is my method is theoretically correct? Is it a good idea to do it this way? Or, are there any obvious pitfalls to this method? If so, can anyone please recommend me a better approach?
Second question: I could probably figure it out myself with some trials. But still I am posting this because this could potentially render the approach as unusable. The problem is the compilation error:
In function `main':
main.cpp:(.text+0x9): undefined reference to `getVariant()'
collect2: error: ld returned 1 exit status