1. 程式人生 > >外部檔案呼叫結構體變數

外部檔案呼叫結構體變數

//file: head.h

struct test

{ int i;

char j;

}; // 這裡不能定義任何變數,因為標頭檔案被許多檔案包含,會出現重複定義

extern struct test *right; // 申明結構體變數 right 在其它檔案中定義

/*******************************************************/



//file: use.c

struct test *right; // 在這裡將 right 定義為全域性變數



//file: other.c

#include "head.h" // 只要將標頭檔案包含進去,任何檔案都可以呼叫 right;



void over()

{ printf("%c",right->j); // 直接呼叫結構體變數 right 的成員





感謝大家的參與!

樓下有些朋友提到了這種觀點:一個變數可以多次申明,不管是否在一個檔案中,申明和定義可以同時出現。我做了錯誤的反駁,特此說明。





例子:

test.h:

typedef struct

{

int a;

char b[12];

} test;



extern test *t;

***********************************************************************

test.c:

#include ;

#include ;

#include "test.h"



test *t;

int main()

{

t = (test *)malloc(sizeof(test));

t->;a = 2;

strcpy(t->;b,"abc");

test_func();

free(t);

return 0;

}

************************************************************************

test_func.c:

#include ;

#include "test.h"



void test_func()

{

printf("t->;b = %s/n",t->;b);

}