头包括在多个C文件 [英] Headers include in multiple C files

查看:109
本文介绍了头包括在多个C文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件的foo.c和bar.c,我与单独的gcc编译-c ,然后链接。这两个文件需要stdio.h和stdlib.h中头。

I have two files foo.c and bar.c that I compile separately with gcc -c and then link. Both files need the stdio.h and stdlib.h headers.

我必须包括他们在两者兼而有之?不觉得有点多余?我是否应该使用可能#IFDEF?

Do I have to include them in both? Doesn't feel a little redundant? Should I maybe use #ifdef?

什么是最好的做法是什么?

What's the best practice?

推荐答案

每个C文件是一个不同的翻译单元的。换句话说,它是一个的整个单独的程序的,语法完整和正确的。因此,每个C文件必须的编译的独立于任何其他的C文件,并且必须包含每个标识符,它使用,而不管这些声明是否也出现在其他C文件中每声明。但从编译器来看,每个C文件本身就是一个完整的程序(虽然未解决的引用)。

Each C file is a different translation unit. In other words, it is an entire separate program, syntactically complete and correct. Thus, each C file must compile independently of any other C file, and must contain every declaration for every identifier it uses, regardless of whether these declarations also appear in other C files. From the compiler point of view, each C file is a complete program by itself (albeit with unresolved references).

头文件的是,按照惯例,文件包含必须出现在C组文件声明。这是一个简单的文本复制和粘贴在包括点 - - 头文件可以由preprocessor被包括在内。为方便避免手动转换单元之间复制声明

Header files are, by convention, files that contains declarations that must appear in a group of C files. Header files can be included by the preprocessor -- which is a simple textual copy-and-paste at the include point -- as a convenience to avoid manually duplicating declarations between the translation units.

总结:这是不是多余的,包括在不同的C文件相同的文件 - 它被正式要求

Summing up: it is not redundant to include the same files in different C files -- it is formally required.

(之后,您的链接的目标文件,这只是小程序,到一个更大的最后方案,较大的程序大致是较小的子程序的总和,它们之间解决了所有引用。一般而言,链接阶段不知道生成生成的目标文件的原始文件的语言结构什么。)

(Afterwards, you link object files, which are just smaller programs, into a larger final program. The larger program is roughly a summation of smaller subprograms, with all references resolved between them. Generally speaking, the linking phase does not know anything about the language structure of the original files that generated the resulting object file.)

这篇关于头包括在多个C文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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