我是否需要包含我所包含文件所依赖的文件?

时间:2015-08-04 19:13:20

标签: c

我在目录中有一个名为coderTest.c的C程序。在一个子目录src中,我有几个文件,one.c,two.c,three.c,以及它们相关的头文件one.h,two.h,three.h。

我想在coderTest.c中使用one.c和two.c中的函数。 one.c和two.c都使用three.c中的函数。我是否需要在coderTest.c中包含three.c,或者它是否会依赖它自己的依赖?

我正在使用#include "src/one.h"一两个。

4 个答案:

答案 0 :(得分:2)

  

我是否需要在coderTest.c中包含three.c,否则它会照顾   它依赖于它自己吗?

您不需要在"src/three.h"中包含coderTest.c,但这并不意味着编译器会自动处理依赖项。此标头需要包含在one.ctwo.cthree.c中。最后一个是确认标题的声明和定义是否相互匹配。

因此,您的项目可能看起来像:

coderTest.c

#include "src/one.h"
#include "src/two.h"
// ...

src/one.c

#include "one.h"
#include "three.h"
// ...

src/two.c

#include "two.h"
#include "three.h"
// ...

src/three.c

#include "three.h"
// ...

要防止多个包含相同标头,请分别对每个标头文件使用header guards

答案 1 :(得分:0)

只要two.cone.c正确#include "three.h",编译器就可以将依赖关系链接在一起而不会出现问题。如果您想在three.c中运行来自coderTest.c的内容,则还希望您在其中#include它。

您的文件是否具有预处理器指令#IFNDEF#DEFINE#ENDIF以防止重复导入?

答案 2 :(得分:0)

在coderTest.c中,包含以下内容: #include "src/two.h #include "src/one.h

在one.c中,包括: #include "src/three.h

在two.c中,包括: #include "src/three.h

  

我是否需要在coderTest.c中包含three.c,还是它会依赖它自己的依赖?

不,你不需要在coderTest.c中包含three.c,因为one.c和two.c将它抽象出来。

答案 3 :(得分:0)

只要提供对必要原型的可见性,您就可以通过多种方式执行操作。除了最好包含头文件的位置之外,请考虑使用 wrappers 来保证您的标头只使用一次:

 #ifndef _SOMEFILE_H_
 #define _SOMEFILE_H_

     the entire file

 #endif /* SOMEFILE_H__SEEN */  

还要考虑可读性。例如:coderTest.c,one.c / .h,two.c / .h,three.c / .h如你所述:
1) 您应该在one.c和two.c中包含three.h.

2) 对于coderTest.c,可以在文件本身 中包含所有支持标题的#include标头在收集器标题中:conderTest.h:

coderTest.h:

#include "./src/one.h"
#include "./src/two.h"
#include "./src/three.h"

coderTest.c

#include "coderTest.h"