C/C++の「ヘッドファイルガード」

1360 ワード

Objective Cでは#importで重複包含を防ぐことができるが、C/C++では異なり、「ヘッダファイルガード」しか使えない.
       
次のプログラムはエラーです.
// global.h   

// #ifndef GLOBAL
// #define GLOBAL

int total = 0;

// #endif

 
//test.h   

// #ifndef TEST
// #define TEST

#include "global.h"

// #endif

 
// main.c   

#include <stdio.h>
#include "global.h"
#include "test.h"

int main()
{
	int i = total;
	printf("%d
", i); return 0; }

 
 
重複を防止する「ヘッダー・ファイル・ガード」メカニズムに変更する必要があります.以下のようにします.
// global.h   

#ifndef GLOBAL
#define GLOBAL

int total = 0;

#endif

 
//test.h   

#ifndef TEST
#define TEST

#include "global.h"

#endif

 
// main.c   

#include <stdio.h>
#include "global.h"
#include "test.h"

int main()
{
	int i = total;
	printf("%d
", i); return 0; }

「ヘッダファイルガード」を加えると、プログラムは正常に動作する.