根据 #define 动态编译文件

Dynamically compile files in depending of #define

本文关键字:文件 编译 动态 #define 根据      更新时间:2023-10-16

我有一个项目应用程序,在这个项目中我有两个文件夹"behavior1"和"behavior2"

Application
|_ behaviour1
| |_ action
|   |_ action.h
|   |_ action.cpp
|
|_ behaviour2
| |_ action
|   |_ action.h
|   |_ action.cpp
|
|_ behaviour_type.h
|_ app.cpp

其中每个目录中的 action.h 从抽象类定义派生类

class AbstractAction {
   public:
       virtual ~AbstractAction() = default;
       virtual void Execute() = 0;
}

但实现是不同的。

然后通过使用文件"behaviour_type.h"中的下一个代码

#define CURRENT_BEHAVIOUR bevahiour1
#define QUOTEME_1(x) #x
#define QUOTEME(x) QUOTEME_1(x) 
#define INCLUDE_FILE(x) QUOTEME(CURRENT_BEHAVIOUR/x)

在"应用程序.cpp"中我可以写

#include "behavior_type.h"
#include INCLUDE_FILE(hook/action.h)
...
AbstractAction* action = new Action();
action->Execute();

但是在这种情况下,将编译两个"action.h"(来自 behavior1 和 behavior2)。我只想编译一个,我把它包括在内。可能吗仅使用源代码(即 my INCLUDE_FILE 指令)编译一个"action.h"文件,而不使用编译器属性。

也许这个问题很傻,对不起,但我是这里的新手。谢谢。

我不知道您的宏做什么或应该实现什么,但为什么不使用简单的变体:

#ifdef ACTION_1
    #include "behaviour1/hook/action.h"
#else
    #include "behaviour2/hook/action.h"
#endif
AbstractAction* action = new Action();
action->Execute();

也就是说,我完全支持那些说你应该同时拥有两者并使用某种模式而不是条件编译的评论。