2016-10-03 96 views
-1

我是新來的這個領域。 我正在嘗試閱讀一個示例程序。同名.h和.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生成目標文件後。當我在終端運行. some forlder/part1a,它運行良好,輸出內容爲team

我有兩個令人困惑的地方。 1.我對團隊的定義感到困惑,其價值在team.c中給出,但在support.hextern中定義的值用於再次獲取,程序運行時的順序是什麼? 2.如果support.h和support.c有任何其他關係,它們的名稱是否相同?

+0

這些是通過閱讀C書或教程更好地解答的基本C問題。或者進行搜索,因爲這些基本概念已經處理過很多次了。 – kaylum

回答

0

.h通常用於頭文件。頭文件通常用於聲明諸如類/結構體和函數之類的內容而不實現它們。在這種情況下,team.h聲明瞭team struct和check_team函數,而support.c正在定義check_team。編譯器知道如何將這些不同的部分放在一起。同樣,雖然support.h和support.c確實共享一個名稱,但這不是他們爲什麼有關係,而僅僅是一種約定。通常你會得到一些像team.h這樣的頭文件,你可以將它包含在所有需要它的文件中,然後在其他地方實現。但是命名約定不會強制關係。