C++ 根据链接所针对的类而改变行为的程序

C++ 根据链接所针对的类而改变行为的程序,c++,plugins,linker,extern,C++,Plugins,Linker,Extern,我不认为我所尝试的足够花哨,值得使用“插件”这个词,但这里我要做的是: 给定文件a.h、a.cpp和main.cpp,我想创建其他文件,例如: g++ -o test main.cpp a.cpp b.cpp 结果是测试程序做了一些事情,并且 g++ -o test main.cpp a.cpp c.cpp 做点别的 这部分我已经在工作了,下面是cf代码。 我的问题是:有没有可能 g++ -o test main.cpp a.cpp 做一些默认行为?我尝试了好几件事,但最终总是得到一些未

我不认为我所尝试的足够花哨,值得使用“插件”这个词,但这里我要做的是:

给定文件a.h、a.cpp和main.cpp,我想创建其他文件,例如:

g++ -o test main.cpp a.cpp b.cpp
结果是测试程序做了一些事情,并且

g++ -o test main.cpp a.cpp c.cpp
做点别的

这部分我已经在工作了,下面是cf代码。 我的问题是:有没有可能

 g++ -o test main.cpp a.cpp
做一些默认行为?我尝试了好几件事,但最终总是得到一些未定义的东西

到目前为止,我掌握的代码是:

// a.h    

#ifndef A_H_
#define A_H_

class A {
 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 A {
 public:
  B();
  ~B();
  void print();
};


// b.cpp

#include <iostream>
#include "b.h"

B::B(){}
B::~B(){}
void B::print(){
  std::cout << "I am B" << std::endl;
}

A* a = new B();


//  code in c.h and c.cpp similar to the one in b.h and b.cpp
//   just "B" replaced by "C"

// main.cpp

#include "a.h"

extern A* a;

int main(){
  a->print();
}
让测试不执行任何操作或执行默认行为。不需要简单。

这里有一个使用弱符号的(不可移植)选项

a、 h main.cpp 捕获信号
#包括“a.h”
#包括
结构B:A
{
void print()覆盖{

cout看起来很棒!没有任何globals是一个很好的加号。你说的“不可移植”是什么意思?我应该知道有什么限制吗?C(或C++)标准没有提到这类事情,所以没有使用这种技术的可移植解决方案(可能有使用其他技术的便携式解决方案,但我不知道有一种)。语法是GCC语法,clang可能支持它,也可能支持其他一些语法。不适用于MSVC,但其他编译器/链接器可能具有类似的功能。似乎对我有用,但我会等待一段时间再接受,以防有人提出更可移植的解决方案。
g++ -o test main.cpp a.cpp
struct A {
  public:
    virtual void print() = 0;
};

struct Dummy: A {
  void print() override {};
};

A* init();
#include "a.h"

A* __attribute__((weak)) init()
{
  return new Dummy;
}

int main()
{
  A* a = init();
  a->print();
}
#include "a.h"
#include <iostream>

struct B: A
{
  void print() override {
    std::cout << "B" << std::endl;
  }
};

A* init()
{
  return new B;
}