如何构建#包括用C [英] How to structure #includes in C

查看:158
本文介绍了如何构建#包括用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个C程序,它坏了一组* .c和* .h文件。如果从一个文件code从另一个文件使用的功能,我应该在哪里包含头文件?里面所​​使用的功能,或* .c文件的文件头中?

Say I have a C program which is broken to a set of *.c and *.h files. If code from one file uses functions from another file, where should I include the header file? Inside the *.c file that used the function, or inside the header of that file?

例如。文件 foo.c的包括 foo.h中,它包含了 foo.c的<所有声明/ code>;同为 bar.c bar.h 。功能 foo1() foo.c的通话 BAR1(),这是 bar.h 和 bar.c 。现在的问题是,我应该包括 bar.h foo.h中,或内部 foo.c的

E.g. file foo.c includes foo.h, which contains all declarations for foo.c; same for bar.c and bar.h. Function foo1() inside foo.c calls bar1(), which is declared in bar.h and defined in bar.c. Now the question is, should I include bar.h inside foo.h, or inside foo.c?

什么是一个很好的一套规则经验法则对于这样的问题?

What would be a good set of rules-of-thumb for such issues?

推荐答案

您应该包括内部foo.c. foo.h中包括foo.h中这样其他的C文件将不携带bar.h不必要的。这是我的忠告,包括头文件:

You should include foo.h inside foo.c. This way other c files that include foo.h won't carry bar.h unnecessarily. This is my advice for including header files:


  • 添加包括在C文件的定义 - 这种方式读code当文件依赖性更为明显

  • 拆分foo.h中在两个单独的文件,说foo_int.h和foo.h.第一种只携带由foo.c.所需要的类型和前瞻性声明该foo.h中包括由外部模块所需要的功能和类型。这有点像foo的私人和公共部分。

  • 避免交叉引用,即富引用酒吧和酒吧引用foo的。这可能会导致连接问题,也是不好的设计的征兆

这篇关于如何构建#包括用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆