C ++预处理器如何工作? [英] How does C++ Preprocessors work?
问题描述
我目前正在研究开源C ++项目,以了解有关C ++的更多信息.我正在查看的项目之一位于:
I am currently looking at open source C++ projects to learn more about C++. One of the project I am look at is located at:
https://github.com/Myzilla-Web-Resources/OpenBlox/
我了解大多数来源,但我不了解的是他如何使用预处理器声明C ++类.
I understand most of the source, but something I don't understand is how he is using the Preprocessors to declare a C++ class.
例如,
static_init.h
static_init.h
#define DECLARE_STATIC_INIT(ClassName) \
static void static_init_func(); \
static OpenBlox::static_init_helper ClassName##_static_init_helper
namespace OpenBlox{
class static_init_helper{
public:
static_init_helper(init_func_type f){
static_init::instance().add_init_func(f);
}
};
Instance.h
Instance.h
#define DECLARE_CLASS(Class_Name) \
virtual Instance* cloneImpl(); \
virtual QString getClassName(); \
virtual int wrap_lua(lua_State* L); \
DECLARE_STATIC_INIT(Class_Name); \
protected: \
static QString ClassName; \
static QString LuaClassName
Frame.h
namespace ob_instance{
class Frame: public GuiObject{
public:
Frame();
virtual ~Frame();
virtual void render();
DECLARE_CLASS(Frame);
};
}
#endif
请注意,Frame.h继承了所有Instance.h函数/处理器.有人可以向我解释这是如何工作的吗?
Please note that Frame.h inherited all of Instance.h functions/processors. Could someone explain to me how this work?
推荐答案
预处理器只是查找和替换文本,因此在显示的 Frame
定义中,预处理器首先看到 DECLARE_CLASS(框架)
,并将其替换为 DECLARE_CLASS
宏的内容,成为
The preprocessor is just a text find and replace, so in the Frame
definition you showed, the preprocessor first sees DECLARE_CLASS(Frame)
and replaces it with the content of the DECLARE_CLASS
macro, becoming
namespace ob_instance{
class Frame: public GuiObject{
public:
Frame();
virtual ~Frame();
virtual void render();
virtual Instance* cloneImpl();
virtual QString getClassName();
virtual int wrap_lua(lua_State* L);
DECLARE_STATIC_INIT(Frame);
protected:
static QString ClassName;
static QString LuaClassName;
};
}
(我整理了格式,实际上整个替换文本都在一行上.)
(I cleaned up the formatting, in reality the entire replacement text is on one line).
然后备份到插入文本之前,再次开始通读,并看到 DECLARE_STATIC_INIT(Frame)
并替换为:
It then backs up to just before the text it inserted, starts reading through again, and sees DECLARE_STATIC_INIT(Frame)
and replaces that:
namespace ob_instance{
class Frame: public GuiObject{
public:
Frame();
virtual ~Frame();
virtual void render();
virtual Instance* cloneImpl();
virtual QString getClassName();
virtual int wrap_lua(lua_State* L);
static void static_init_func();
static OpenBlox::static_init_helper Frame_static_init_helper;
protected:
static QString ClassName;
static QString LuaClassName;
};
}
( ##
是令牌连接运算符)
为您提供最终的 Frame
类定义.
Giving you the final Frame
class definition.
正如Chris Beck在评论中提到的那样,您可以使用 -E
标志对gcc或clang进行编译,使编译器输出预处理的文件,而不是对其进行编译.
As mentioned by Chris Beck in the comments, you can use the -E
flag to gcc or clang to have the compiler output the preprocessed file instead of compiling it.
这篇关于C ++预处理器如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!