c++ - Program which behavior changes depending on classes it is linked against -


i not think attempt fancy enough deserve term "plugin" here trying do:

given files a.h, a.cpp , main.cpp, create other files such as:

g++ -o test main.cpp a.cpp b.cpp 

results in test program doing something, ,

g++ -o test main.cpp a.cpp c.cpp 

does else.

this part have working, cf code below. issue is: possible have

 g++ -o test main.cpp a.cpp 

do default behavior? tried several things, end undefined.

code have far:

// a.h      #ifndef a_h_ #define a_h_  class {  public:   a();   ~a();   virtual void print()=0; };  #endif   // a.cpp  #include <iostream> #include "a.h"  a::a(){} a::~a(){}   // b.h  #include "a.h"  class b: public {  public:   b();   ~b();   void print(); };   // b.cpp  #include <iostream> #include "b.h"  b::b(){} b::~b(){} void b::print(){   std::cout << "i b" << std::endl; }  a* = new b();   //  code in c.h , c.cpp similar 1 in b.h , b.cpp //   "b" replaced "c"  // main.cpp  #include "a.h"  extern a* a;  int main(){   a->print(); } 

when compiling against b.cpp, code prints "i b", when compiling against c.cpp, code prints "i c".

i like:

g++ -o test main.cpp a.cpp 

to have test either nothing or default behavior. not need simple.

here's (non-portable) option using weak symbols.

a.h

struct {   public:     virtual void print() = 0; };  struct dummy: {   void print() override {}; };  a* init(); 

main.cpp

#include "a.h"  a* __attribute__((weak)) init() {   return new dummy; }  int main() {   a* = init();   a->print(); } 

b.cpp

#include "a.h" #include <iostream>  struct b: {   void print() override {     std::cout << "b" << std::endl;   } };  a* init() {   return new b; } 

if don't link b.cpp or other entity provides init function, 1 in main.cpp used. if link b.cpp, one's definition used.

this sort of provides "default implementation" init function, , lets manage initialization not using globals (not important here, can more tricky once flesh out plugin system).


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -