如何在 C 中构造#includes [英] How to structure #includes in C

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

问题描述

假设我有一个 C 程序,它被分解为一组 *.c 和 *.h 文件.如果一个文件中的代码使用另一个文件中的函数,我应该在哪里包含头文件?在使用该函数的 *.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 的所有声明;bar.cbar.h 相同.foo.c内的foo1()函数调用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 文件中添加包含定义 - 这样在阅读代码时文件依赖关系更加明显.
  • 将 foo.h 拆分为两个单独的文件,例如 foo_int.h 和 foo.h.第一个带有只有 foo.c 需要的类型和前向声明.foo.h 包含外部模块所需的函数和类型.这类似于 foo 的私有和公共部分.
  • 避免交叉引用,即 foo 引用 bar 和 bar 引用 foo.这可能会导致链接问题,也是设计不良的标志

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

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