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

标签 c++ compilation

我想创建一个程序,它的行为取决于要编译的兼性附加源代码文件(有些人可能会在其中添加一些不同的功能)。我想到了函数重载,类似于(不可编译的)以下代码:

文件1.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();
 }

文件2.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

应该生成具有不同输出的可执行文件。 是否有可能满足该需求?

最佳答案

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

文件1.cpp:

#include <iostream>

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

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

文件2.cpp:

#include <iostream>

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

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

文件1.h:

class Base
{
    virtual void printOut();
}

文件1.cpp

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

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

文件2.cpp:

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

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

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

文件1.h:

class Base
{
    virtual void printOut();
}

文件1.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();
}

文件2.h:

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

文件2.cpp:

void Derived::printOut()
{
}

并用

编译
g++ file1.cpp
在一种情况下和
g++ -DUSE_DERIVED file1.cpp file2.cpp
在另一个。

关于C++ 程序行为取决于源代码文件集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37556706/

相关文章:

linux - 无法使用sudo命令编译cuda

java - 无法使用 apktool : "Asset package include not found" 编译应用程序

c++ - 函数外的代码

Java加载一个DLL,该DLL从JNI中的另一个DLL导出方法

tensorflow - 使用CUDA 9.1编译的tensorflow

css - 应用程序.jsx :11 Uncaught TypeError: Cannot read property 'TodoComponent' of undefined

swift - Swift 的 XCode 7 编译错误

c++ - 共享库和静态库如何选择?

c++ - 在C++中,不同的游戏实体应该有不同的类吗?或者它应该在一个包含所有行为的类中吗?

c++ - 是否可以在正则表达式中命名子模式,然后通过 C++ 中的子模式名称提取匹配项?