简体   繁体   English

我们是否应在.h和.cpp文件中都包含宏(#define)

[英]Should we include a macro(#define) in both .h & .cpp files

If i use them in both the files. 如果我在两个文件中都使用它们。 Going with the term "macro" in c++ it's just a replacement mechanism(doesn't know anything about c++ structure) that happens in pre-compilation stage. 与c ++中的“宏”一起使用,它只是在预编译阶段发生的一种替换机制(对c ++结构一无所知)。

Is this the reason that i should define macro(#define) in both the files or doesn't need to do that or am i missing anything.? 这是我应该在两个文件中都定义宏(#define)还是不需要这样做的原因,或者我什么都没有。

在.h文件中定义宏,然后仅在.cpp文件中包含该.h文件就足够了。

Assume a simple case first. 首先假设一个简单的案例。 You have the .cpp file using the .h file: 您具有使用.h文件的.cpp文件:

  • Car.cpp Car.cpp
  • Car.h 汽车

If you have a constant, say: #define KM_PER_MINUTE 3 . 如果您有常数,请说: #define KM_PER_MINUTE 3 If this constant is used by any function inside the .h file, put this #define in the .h file: 如果.h文件中的任何函数使用此常量,请将此#define放在.h文件中:

Inside Car.h:
#ifndef CAR_H
#define CAR_H
... 
#define KM_PER_MINUTE 3
...
int calculate_total_KM(int minute) 
{
    return minute * KM_PER_MINUTE;
}
...
#endif 

On the other hand, if this constant is used only in the .cpp file, put this #define in the .cpp file: 另一方面,如果仅在.cpp文件中使用此常量,请将此#define放在.cpp文件中:

Inside Car.cpp:
#define KM_PER_MINUTE 3
...
int calculate_total_KM(int minute) 
{
    return minute * KM_PER_MINUTE;
}
...

From the documentation : 文档中

The #define directives define the identifier as macro, that is instruct the compiler to replace all successive occurrences of identifier with replacement-list, which can be optionally additionally processed. #define指令将标识符定义为宏,这指示编译器将所有后续出现的标识符替换为“替换列表”,可以选择对其进行附加处理。 If the identifier is already defined as any type of macro, the program is ill-formed unless the definitions are identical. 如果标识符已经定义为任何类型的宏,则除非定义相同,否则程序格式错误。

I guess it fully replies to your question. 我想它完全可以回答您的问题。
It goes without saying that you can define a macro in a .h file, then include it wherever you need that macro. 不用说,您可以在.h文件中定义一个宏,然后在需要该宏的任何地方包括它。

If you put it in #ifndef then it doesn't matter, it will be included only once (the first occurrence). 如果将其放在#ifndef则没关系,它将仅包含一次(第一次出现)。 I you doesn't, then you'll get warning for already defined macro when the macro defined in the source and also the header with the macro included. 如果您没有,那么当源中定义的宏以及包含宏的标头中时,您将收到已定义宏的警告。

BTW: There is a third place, you can declare the macro in the makefile, or project settings. 顺便说一句:第三名,您可以在生成文件或项目设置中声明宏。

'define macro(#define) in both the files' cause redefinition error or warning. “在两个文件中都定义宏(#define)”会导致重新定义错误或警告。 It's not good. 这不好。 It may cause program compile error(good thing), or runtime error(terrible thing). 它可能会导致程序编译错误(好东西)或运行时错误(糟糕的事情)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM