C ++程序行为取决于源代码文件集

时间:2016-05-31 22:31:45

标签: c++ compilation

我想创建一个程序,其行为不同,具体取决于要编译的兼容性附加源代码文件(某些人可能会添加一些不同的功能)。我考虑过函数重载,类似于(不可编译的)以下代码:

file1.cpp:

 #include <iostream>
 #include <string.h>
 using namespace std;

 class base {
  public:
   void ausgeb() { cout<<"here output base"<<endl; }
 };

 class derive: public base;

 int main(int argc, char** argv)
 {
  derive beisp;
  beisp.ausgeb();
 }

file2.cpp:

  #include <iostream>
  #include <string.h>
  using namespace std;
  class base;
  class derive : public base
  {
   public:
   void ausgeb() { cout<<"here output derive"<<endl; }
  };

现在我希望:

g++ -o o1 file1.cpp file2.cpp

g++ -o o2 file1.cpp

应生成具有不同输出的可执行文件。 可能有可能满足这种需求吗?

1 个答案:

答案 0 :(得分:2)

这个解决方案是gcc特有的,如果你切换编译器,它很可能不再工作了......

file1.cpp:

#include <iostream>

void printOut() __attribute__((weak));
void printOut()
{
    ::std::cout << "weak" << ::std::endl;
}

int main(int, char*[])
{
    printOut();
    return 0;
}

file2.cpp:

#include <iostream>

void printOut()
{
    ::std::cout << "strong" << ::std::endl;
}

更高级(省略了printOut实现):

file1.h:

class Base
{
    virtual void printOut();
}

file1.cpp

#include "file1.h"
Base& getInstance() __attribute__((weak));
Base& getInstance()
{
    static Base theInstance;
    return theInstance;
}

int main(int, char*[])
{
    Base& instance = getInstance();
    instance.printOut();
}

file2.cpp:

#include "file1.h"
class Derived : public Base
{
    virtual void printOut();
}

Base& getInstance()
{
    static Derived theInstance;
    return theInstance;
}

更通用的解决方案,通过定义预处理器符号:

file1.h:

class Base
{
    virtual void printOut();
}

file1.cpp

#include "file1.h"
#ifdef USE_DERIVED
#include "file2.h"
#endif

void Base::printOut()
{
}

int main(int, char*[])
{
#ifdef USE_DERIVED
    Derived instance;
#else
    Base instance;
#endif
    instance.printOut();
}

file2.h:

#include "file1.h"
class Derived : public Base
{
    virtual void printOut();
}

file2.cpp:

void Derived::printOut()
{
}

在一个案例中使用

g++ file1.cpp
进行编译,在另一个案例中使用
g++ -DUSE_DERIVED file1.cpp file2.cpp
进行编译。

相关问题