在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\n", 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\n", i);

	return 0;
}


      加上“头文件卫士”后,程序可以正常运行.


本文转载:CSDN博客