假设我有a.h,它包含以下内容:
<stdbool.h>
<stddef.h>
<stdin.h>假设我也有包含<stdbool.h>的b.h。如果a.h中有#ifndef预处理器定义语句,而b.h中没有,那么a.h会只包含b.h中没有包含的内容吗?那么,当b.h包含a.h时,a.h是否包含stddef.h和stein.h而不重新包含stdbool.h,或者这些预处理器定义函数是否仅用于查看整个类是否已重新定义,而不是其中的特定函数?
编辑:
另外,假设b.h包含另一个包含stdbool.h的头文件,-that使b.h同时具有来自该类和a.h的stdbool.h。这会导致错误吗?
发布于 2012-03-14 03:16:53
所有的C标准标头都必须以任意顺序多次包含:
标准标头可以以任何顺序包含;每个标头可以在给定范围内包含多次,与只包含一次
没有什么不同
发布于 2012-03-14 03:13:47
如果stdbool.h本身有include guards (#ifndef),那么一切都会很好。否则,您可能会两次包含一些头文件。会有问题吗?那得看情况。如果包含两次的头文件只包含声明,那么所有内容都将被编译--只需多花几纳秒的时间。想象一下:
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();
}另一方面,如果存在定义,则会导致错误:
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();
}发布于 2012-03-14 03:52:25
正常情况下,大多数标题都以
#ifndef _HEADERFILENAME_H_
#define _HEADERFILENAME_H_并以下面一行结束:
#endif如果您两次包含一个标头,那么第二次由于#ifndef、#define和#endif的原因,您的程序将不再包含完整的标头
https://stackoverflow.com/questions/9690212
复制相似问题