如何在C中链接多个实现文件 [英] How to link multiple implementation files in C
问题描述
我有许多 .c
文件,即实现文件说
I have a number of .c
files, i.e. the implementation files say
- main.c
- 交流
- B.c
任何文件中的函数都可以调用不同文件中的任何函数.我的问题是,我是否需要一个 .h
即 A 和 B 的每个实现的头文件,其中每个头文件都定义了 A 或 B 中的 ALL 函数.
Where functions from any of the files can call any function from a different files. My question being, do I need a .h
i.e. header file for each of A and B's implementation where each header file has the definition of ALL the functions in A or B.
另外,main.c 中会同时包含 A.h
和 B.h #included
吗?
Also, main.c will have both A.h
and B.h #included
in it?
如果有人终于可以说清楚,还有,我以后如何在终端中编译和运行多个文件.
If someone can finally make it clear, also, how do I later compile and run the multiple files in the terminal.
谢谢.
推荐答案
标题内容
A.c
的标头 A.h
应该只包含使用 A.c
中定义的工具的外部代码所必需的信息.它不应该声明静态函数;它不应该声明静态变量;它不应声明内部类型(仅在 A.c
中使用的类型).它应该确保文件可以只使用#include "A.h"
,然后充分利用A.c
发布的功能.它应该是独立的、幂等的(因此您可以包含它两次而不会出现任何编译错误)并且最小化.您可以通过将 #include "A.h"
作为 A.c
中的第一行 #include
来简单地检查标头是否是独立的;您可以通过两次包含它来检查它是否是幂等的(但最好作为单独的测试完成).如果它不编译,它就不是自包含的.B.h
和 B.c
也是如此.
Header contents
The header A.h
for A.c
should only contain the information that is necessary for external code that uses the facilities defined in A.c
. It should not declare static functions; it should not declare static variables; it should not declare internal types (types used only in A.c
). It should ensure that a file can use just #include "A.h"
and then make full use of the facilities published by A.c
. It should be self-contained, idempotent (so you can include it twice without any compilation errors) and minimal. You can simply check that the header is self-contained by writing #include "A.h"
as the first #include
line in A.c
; you can check that it is idempotent by including it twice (but that's better done as a separate test). If it doesn't compile, it is not self-contained. Similarly for B.h
and B.c
.
有关标头和标准的更多信息,请参阅'我应该使用#include
in headers?',它引用了 NASA 编码标准,以及 '链接到静态库',其中包含一个脚本chkhdr
,我用它来测试自包含性和幂等性.
For more information on headers and standards, see 'Should I use #include
in headers?', which references a NASA coding standard, and 'Linking against a static library', which includes a script chkhdr
that I use for testing self-containment and idempotency.
注意main.o
依赖于main.c
、Ah
和Bh
,但是main.c
本身不依赖于头文件.
Note that main.o
depends on main.c
, A.h
and B.h
, but main.c
itself does not depend on the headers.
说到编译,你可以使用:
When it comes to compilation, you can use:
gcc -o program main.c A.c B.c
如果您需要其他选项,请添加它们(开头的大多数标志;最后的库,在源代码之后).您也可以将每个文件分别编译为目标代码,然后将目标文件链接在一起:
If you need other options, add them (most flags at the start; libraries at the end, after the source code). You can also compile each file to object code separately and then link the object files together:
gcc -c main.c
gcc -c A.c
gcc -c B.c
gcc -o program main.o A.o B.o
这篇关于如何在C中链接多个实现文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!