我是这个领域的新手。 我正在尝试阅读一个示例程序。
第一个是team.c
#include "support.h"
struct team_t team = {
"", /* first member name
"", /* first member email
"", /* second member name
"" /* second member email
};
它包括support.h
,即:
#ifndef SUPPORT_H__
#define SUPPORT_H__
/*
* Store information about the team who completed the assignment, to
* simplify the grading process. This is just a declaration. The definition
* is in team.c.
*/
extern struct team_t {
char *name1;
char *email1;
char *name2;
char *email2;
} team;
/*
* This function verifies that the team name is filled out
*/
void check_team(char *);
#endif // SUPPORT_H__
check_team
功能位于support.c
:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "support.h"
/*
* Make sure that the student names and email fields are not empty.
*/
void check_team(char * progname) {
if ((strcmp("", team.name1) == 0) || (strcmp("", team.email1) == 0)) {
printf("%s: Please fill in the team struct in team.c\n",
progname);
exit(1);
}
printf("Student 1 : %s\n", team.name1);
printf("Email 1 : %s\n", team.email1);
printf("Student 2 : %s\n", team.name2);
printf("Email 2 : %s\n", team.email2);
printf("\n");
}
最后,在part1a.c中:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include "support.h"
int main(int argc, char **argv) {
check_team(argv[0]);
/*some other code*/
return 0;
}
使用makefile生成目标文件后。当我在终端中运行. some forlder/part1a
时,它可以很好地输出team
我有两个令人困惑的地方。 1.我对团队的定义感到困惑,在team.c
中给出但在support.h
和extern
中定义的值再次得到,程序运行时的顺序是什么? 2. support.h和support.c是否有相同的名称,如果它们有任何其他关系?
答案 0 :(得分:0)
.h通常用于头文件。头文件通常用于声明诸如类/结构和函数之类的东西而不实现它们。在这种情况下,team.h声明了team struct和check_team函数,而support.c正在定义check_team。编译器知道如何将这些不同的部分组合在一起。另外,虽然support.h和support.c共享一个名称,但这不是他们有关系的原因,而只是一个约定。通常,您会有一些像team.h这样的头文件,您可以将其包含在需要它的所有文件中,然后在其他地方实现它。但是命名约定不会强制关系。