我想知道C语言中的“Header”是什么意思?是吗:
- 代码中的一个区域,如 HTML 代码中的标题区域(标题>或声明区域?或定义区域?或类似的)?
- 或者它就像一个可以调用的函数(可以是:函数、子例程、作用域或某种类型)。
最佳答案
头文件是 C 程序员普遍接受的约定。
它通常是一个包含在 C 源文件中的 .h 文件,它提供了几个好处。
1.- 提供数据类型、全局变量、常量和函数的声明。
因此您不必一次又一次地重写它们。如果需要更改它们,您只需在单个文件中进行更改。
在示例中,这个由两个编译单元(两个 .c 文件)组成的程序编译并运行得很好。
// File funcs.c
#include <stdio.h>
struct Position {
int x;
int y;
};
void print( struct Position p ) {
printf("%d,%d\n", p.x, p.y );
}
// File main.c
struct Position {
int x;
int y;
};
int main(void) {
struct Position p;
p.x = 1; p.y = 2;
print(p);
}
但是在头文件中声明 struct Position
并且在需要的地方只用 #include
声明会更容易维护,就像这样:
// File funcs.h
#ifndef FUNCS_H
#define FUNCS_H
struct Position {
int x;
int y;
};
#endif // FUNCS_H
//File funcs.c
#include <stdio.h>
#include "funcs.h"
void print( struct Position p ) {
printf("%d,%d\n", p.x, p.y );
}
//File main.c
#include "funcs.h"
int main(void) {
struct Position p;
p.x = 1; p.y = 2;
print(p);
2.- 提供某种类型安全。
C 特性 implicit declaration of functions .在 C99 中修复的“功能”(或者更确切地说是一个有争议的语言设计错误)。
考虑这个由两个 .c 文件组成的程序:
//File funcs.c
#include<stdio.h>
int f(long n)
{
n = n+1;
printf("%ld\n", n );
}
// File main.c
int main(void)
{
f("a");
return 0;
}
使用 gcc 这个程序编译时没有警告或错误。但并不像我们合理期望和期望的那样行事:
jose@cpu ~/t/tt $ gcc -o test *.c
jose@cpu ~/t/tt $ ./test
4195930
使用这样的头文件:
//File funcs.h
#ifndef FUNCS_H
#define FUNCS_H
int f(long n);
#endif // FUNCS_H
//File funcs.c
#include<stdio.h>
int f(long n) {
n = n+1;
printf("%ld\n", n );
}
// File main.c
#include"funcs.h"
int main(void) {
f("a");
return 0;
}
程序仍然编译和运行错误,但至少我们得到了警告:
jose@cpu ~/t $ gcc -o test *.c
main.c: In function 'main':
main.c:5:5: warning: passing argument 1 of 'f' makes integer from pointer without a cast
f("a");
^
In file included from main.c:2:0:
funcs.h:3:5: note: expected 'long int' but argument is of type 'char *'
int f(long n);
^
jose@cpu ~/t $ ./test
4195930
3.- 提供公共(public)接口(interface),同时隐藏实现细节。
当您设计程序时,最好将其模块化。那就是保证它的不同部分(模块)尽可能的独立。这样当您需要对一个模块进行更改时,您不必担心这种更改会影响其他模块
header 有助于做到这一点,因为您将此类模块的用户需要的数据结构、函数原型(prototype)和常量放入模块的 header 中。
实现细节进入 .c 文件。
图书馆就是这样运作的。 API 接口(interface)在头文件中指定和分发。但 API 代码在 .c 文件中,不需要分发。作为该库的用户,您只需要 header 和编译后的库,而不需要它的源代码。
关于c - C Header 在语言上是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38942333/