c - 同名.h和.c文件以及这些文件之间的撤销关系?

标签 c

我对这个领域很陌生。 我正在尝试阅读一个示例程序。

第一个是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生成目标文件后。当我运行 时。终端中的一些 forlder/part1a 效果很好,可以输出 team

的内容

我有两个令人困惑的点。 1. 我对 team 的定义感到困惑,它的值在 team.c 中给出,但在 support.h 中定义,并且 extern 用于获取再说一遍,程序运行时的顺序是什么? 2. support.h和support.c同名,是否有其他关系?

最佳答案

.h 通常用于头文件。头文件通常用于声明类/结构和函数等内容,而不实现它们。在本例中,team.h 声明 team 结构体和 check_team 函数,而 support.c 定义 check_team。编译器知道如何将这些不同的部分组合在一起。另外,虽然 support.h 和 support.c 确实共享一个名称,但这并不是它们之间存在关系的原因,而只是一种约定。通常,您会有一些像 team.h 这样的头文件,您可以将其包含在所有需要它的文件中,然后在其他地方实现它。但命名约定并不强制关系。

关于c - 同名.h和.c文件以及这些文件之间的撤销关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39841273/

相关文章:

c - Widechar 排序并从文件加载

c++ - 返回地址是否确保非 NULL 返回值?

c - 为什么将空节点放入堆栈

c - C代码中忽略的模数操作数

c - yum安装不添加库文件

c++ - sizeof 运算符为 C 和 C++ 返回不同的值?

c - 无论输入如何,strcmp 始终为真

c - c中的开关和大小写如何匹配?

C 中的计算模式——​​数学有点错误

c - 在 C 中使用 LVM_GETITEM 和 SendMessage 获取 LVITEM 的文本