在C源文件和头文件之间的任何根本的区别? [英] Any fundamental difference between source and header files in C?

查看:185
本文介绍了在C源文件和头文件之间的任何根本的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解事情应该用C的源文件和头文件分开。我经常看到很多项目有两套文件具有相同的名称(没有扩展名表示源文件和头文件)。

I don't quite understand how things should be separated in C's source and header files. I often see many projects with two sets of files with the same name (sans the extension denoting source and header files).

到目前为止,从这个缺乏了解,当我写的库,我已经打发所有的类和类方法code到一个文件中,优柔寡断,以选择文件扩展名。

So far, from this lack of understanding, when I've written libraries, I've chucked all the class and class method code into one file, with indecision as to choosing the file extension.

应该是头什么,应该是在源文件中呢?如何实现这种分离?

What should be in headers and what should be in the source files? How do I implement this separation?

推荐答案

有没有的技术的区别。编译器会很乐意让你包括 .C 文件,或者编译 .H 文件中直接,如果你想

There is no technical difference. The compiler will happily let you include a .c file, or compile a .h file directly, if you want to.

有,然而,一个巨大的文化的区别:

There is, however, a huge cultural difference:


  • 声明的(原型)去 .H 文件。在 .H 文件是接口的到任何在相应的 .C 文件中实现

  • Declarations (prototypes) go in .h files. The .h file is the interface to whatever is implemented in the corresponding .c file.

定义的去 .C 文件。他们的实施的在 .H 文件中指定的接口。

Definitions go in .c files. They implement the interface specified in the .h file.

不同的是,一个 .H 文件可以(并且通常会)是的#include D成多个编译单位( .C 文件)。如果你的确定的在 .H 文件中的函数,它会在多个结束的.o 文件和链接器将抱怨多重定义的符号。这就是为什么定义不应该在 .H 文件去。 (内联函数是例外)。

The difference is that a .h file can (and usually will) be #included into multiple compilation units (.c files). If you define a function in a .h file, it will end up in multiple .o files, and the linker will complain about a multiply defined symbol. That's why definitions should not go in .h files. (Inline functions are the exception.)

如果一个函数在 .C 文件中定义,并且希望从其他使用 .C 文件,该函数的声明需要在每个其他 .C 文件可用。这就是为什么你把一个 .H 的#include 的声明,在他们每个人。您也可以重复每个 .C 文件中的声明,但导致很多code复制和unmantainable乱。

If a function is defined in a .c file, and you want to use it from other .c files, a declaration of that function needs to be available in each of those other .c files. That's why you put the declaration in a .h, and #include that in each of them. You could also repeat the declaration in each .c file, but that leads to lots of code duplication and an unmantainable mess.

如果一个函数在 .C 文件中定义,但你的的想从其他 .C 文件,没有必要宣布它在头。它本质上是 .C 文件的实现细节。在这种情况下,做的函数静态一样,所以它不与其他文件中的同名函数冲突。

If a function is defined in a .c file, but you don't want to use it from other .c files, there's no need to declare it in the header. It's essentially an implementation detail of that .c file. In that case, make the function static as well, so it doesn't conflict with identically-named functions in other files.

这篇关于在C源文件和头文件之间的任何根本的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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