c头文件
Simple programs can be put in a single file, but when your program grows larger, it’s impossible to keep it all in just one file.
简单的程序可以放在一个文件中,但是当您的程序变大时,不可能将所有内容都保存在一个文件中。
You can move parts of a program to a separate file, then you create a header file.
您可以将程序的各个部分移至单独的文件,然后创建头文件 。
A header file looks like a normal C file, except it ends with .h
instead of .c
, and instead of the implementations of your functions and the other parts of a program, it holds the declarations.
头文件看起来像普通的C文件,只是头文件以.h
而不是.c
.h
,并且代替声明的函数和程序其他部分的实现,而包含声明 。
You already used header files when you first used the printf()
function, or other I/O function, and you had to type:
首次使用printf()
函数或其他I / O函数时,您已经使用了头文件,并且必须键入:
#include <stdio.h>
to use it.
使用它。
#include
is a preprocessor directive.
#include
是预处理程序指令。
The preprocessor goes and looks up the stdio.h
file in the standard library, because you used brackets around it. To include your own header files, you’ll use quotes, like this:
预处理程序会去在标准库中查找stdio.h
文件,因为您使用了方括号。 要包含自己的头文件,将使用引号,如下所示:
#include "myfile.h"
The above will look up myfile.h
in the current folder.
上面将在当前文件夹中查找myfile.h
。
You can also use a folder structure for libraries:
您还可以对库使用文件夹结构:
#include "myfolder/myfile.h"
Let’s make an example. This program calculates the years since a given year:
让我们举个例子。 该程序计算给定年份以来的年份:
#include <stdio.h>
int calculateAge(int year) {
const int CURRENT_YEAR = 2020;
return CURRENT_YEAR - year;
}
int main(void) {
printf("%u", calculateAge(1983));
}
Suppose I want to move the calculateAge
function to a separate file.
假设我想将calculateAge
函数移至一个单独的文件。
I create a calculate_age.c
file:
我创建了一个calculate_age.c
文件:
int calculateAge(int year) {
const int CURRENT_YEAR = 2020;
return CURRENT_YEAR - year;
}
And a calculate_age.h
file where I put the function prototype, which is same as the function in the .c
file, except the body:
还有一个calculate_age.h
文件,在其中放置了函数prototype ,该函数与.c
文件中的函数相同,除了正文:
int calculateAge(int year);
Now in the main .c
file we can go and remove the calculateAge()
function definition, and we can import calculate_age.h
, which will make the calculateAge()
function available:
现在,在主.c
文件中,我们可以删除并删除calculateAge()
函数定义,并可以导入calculate_age.h
,这将使calculateAge()
函数可用:
#include <stdio.h>
#include "calculate_age.h"
int main(void) {
printf("%u", calculateAge(1983));
}
Don’t forget that to compile a program composed by multiple files, you need to list them all in the command line, like this:
不要忘了要编译由多个文件组成的程序,您需要在命令行中全部列出它们,如下所示:
gcc -o main main.c calculate_age.c
And with more complex setups, a Makefile is necessary to tell the compiler how to compile the program.
对于更复杂的设置,必须有一个Makefile来告诉编译器如何编译程序。
c头文件