2012-03-13 68 views
0

假设我有a.h其中包括以下内容:预处理器的#ifndef

<stdbool.h> 
<stddef.h> 
<stdin.h> 

假设我也有b.h其中还包括<stdbool.h>。如果a.h在其中有#ifndef预处理器定义语句,并且b.h没有。 a.h只会包含b.h中未包含的内容吗?因此,当b.h包括a.h时,a.h将包括stddef.hstein.h而不是重新包含stdbool.h还是那些预处理器定义函数仅用于查看整个类是否被重新定义,而不是其中的特定函数?

编辑:

此外,假定b.h包括另一头文件包括stdbool.h - 即使b.h具有stdbool.h既从该类和a.h。会导致错误吗?

回答

1

所有的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

1

如果stdbool.h本身包含警卫(#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(); 
} 
+1

定义的完整标题一旦你从多个文件中使用相同的头文件,无论如何都会导致链接错误,所以不要这样做。 – 2012-03-13 19:16:46

0

这是正常现象,大多数头开始

#ifndef _HEADERFILENAME_H_ 
#define _HEADERFILENAME_H_ 

和结尾使用以下行:

#endif 

如果包括头两次,第二次你PROGRAMM不会再有因为#ifndef#define#endif