C語言 結構體在多檔案中的定義和宣告

2021-08-21 03:44:05 字數 1000 閱讀 6426

1.結構體可以在.c  .h檔案中多次宣告,不能多次定義

2.不要在標頭檔案中進行變數定義。在a.h中定義了變數str,當main.c和func.c檔案都包含a.h,預處理器會把a.h分別附到兩個原始檔開頭,相當於在main.c和func.c中重複定義了str全域性變數。編譯沒問題,編譯完開始link時,linker會發現main.obj和func.obj中都有str符號,於是報錯,這跟c命名衝突是同一情況。

2.如:typedef宣告結構標記str後,再用str宣告結構變數,會層次分明

程式:

main.c:

/*主函式*/

#include #include "a.h"

//#include "func.c" //加入此宣告會報錯error lnk1169: one or more multiply defined symbols found

//cps student; //在.c 中對結構體的定義

int main()

func.c:

/*函式功能實現*/

#include "a.h"

//#include //不宣告會警告,不會報錯

//cps student;//在.c 中對結構體的定義

void input()

int pw(char c)

a.h:

/*標頭檔案*/

#ifndef a_h_included

#define a_h_included

typedef struct

cps; //在標頭檔案中只能對結構體的進行型別定義和實體宣告

//對於用到該結構體的 .c 要進行實體定義

cps student;//在.h中對student宣告一次或者在兩個.c 檔案中分別宣告,或者在三個檔案中都進行宣告,不然會報錯未宣告

void input(); //對函式的宣告

int pw(char c); //函式宣告

#endif

C語言結構體定義

c語言結構體定義在我看來類似資料庫的表 如 include include struct st1 int id char name 30 char int score int main struct st1 s1 s1.id 1 strcpy s1.name,張三 s1.m s1.score 90 ...

C語言 結構體 定義

c語言允許使用者自己建立由 不同型別資料組成的組合型資料結構 成為結構體。struct student 宣告結構體 一般形式 struct 結構體名 定義結構體變數 1先宣告結構體型別 在定義 struct student student1,student2 2宣告的同時定義變數 struct st...

C語言結構體的定義和使用

在實際問題中,一組資料往往具有不同的資料型別 例如在學生資訊登記表中,姓名為字元型,學號為整型或字元型,年齡為整型,性別為字元型,成績為整型或實型。因為資料型別不同,顯然不能用乙個陣列來存放。在c語言中,可以使用 結構體 struct 來存放一組不同型別的資料。定義結構體的一般形式為 struct ...