[英]Preprocessor #ifndef
Assume I have ah
which includes the following: 假设我有
ah
,其中包括以下内容:
<stdbool.h>
<stddef.h>
<stdin.h>
Assume I also have bh
which also includes <stdbool.h>
. 假设我也有
bh
,其中还包括<stdbool.h>
。 If ah
has the #ifndef
preprocessor definition statement in it and bh
doesn't. 如果
ah
有#ifndef
预处理器定义语句,而bh
没有。 Will ah
include only what hasn't been included in bh
? 请问
ah
只包括bh
没有包含的内容吗? So when bh
includes ah
, will ah
include stddef.h
and stein.h
and not re-include stdbool.h
or are those preprocessor definition functions only used to see whether this whole class is redefined, and not specific functions within it? 所以,当
bh
包括ah
,会ah
包括stddef.h
和stein.h
,而不是重新加入stdbool.h
或仅见惯了这种全班是否被重新定义的预处理器定义的功能,并在它不是具体的功能呢?
EDIT: 编辑:
Also, assume bh
includes another header file which includes stdbool.h
-that makes bh
have stdbool.h
both from that class and ah
. 另外,假设
bh
包含另一个包含stdbool.h
头文件 - 这使得bh
从该类中获得了stdbool.h
和ah
。 Will that cause errors? 这会导致错误吗?
If stdbool.h
itself has include guards ( #ifndef
) then everything will be fine. 如果
stdbool.h
本身包含防护( #ifndef
),那么一切都会好的。 Otherwise you may indeed end up including some headers twice. 否则你可能最终会包含两次标题。 Will it cause a problem?
它会引起问题吗? It depends.
这取决于。 If the twice-included header contains only declarations then everything will compile - it will just take few nanoseconds longer.
如果两次包含的头只包含声明,则所有内容都将编译 - 它只需要几纳秒的时间。 Imagine this:
想象一下:
int the_answer(void); // <-- from first inclusion
int the_answer(void); // <-- from from second inclusion - this is OK
// at least as long as declarations are the same
int main()
{
return the_answer();
}
If on the other hand there will be definitions it will cause an error: 另一方面,如果有定义则会导致错误:
int the_answer(void) // <-- from first inclusion - OK so far
{
return 42;
}
int the_answer(void) // <-- from second inclusion
{ // error: redefinition of 'the_answer'
return 42;
}
int main()
{
return the_answer();
}
All C standard headers must be made such that they can be included several times and in any order: 必须制作所有C标准标题,以便它们可以按任何顺序包含多次:
Standard headers may be included in any order;
标准标题可以按任何顺序包含在内; each may be included more than once in a given scope, with no effect different from being included only once
在给定范围内,每个可以被包括不止一次,与仅被包括一次的效果不同
It's normal that most header start with 大多数标头开始是正常的
#ifndef _HEADERFILENAME_H_
#define _HEADERFILENAME_H_
and end with the following line: 并以以下行结束:
#endif
If you include a header two times, the second time your programm won't include the full header again because of the #ifndef
, #define
and #endif
如果你包括一个标题两次,第二次你的程序将不会再次包含完整的标题,因为
#ifndef
, #ifndef
#define
和#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.