防止头文件重复包含的宏想必大家都清楚,#ifndef#define#endif就是干这个用的,面试中也考过。我也是知道这个宏的作用,今天我们就来实战测试一下,网上说的那是别人的东西,只有自己测试过出结果的才是自己的东西。

[xxx@localhost test]$ ls
a.h  test.c  test.h
[xxx@localhost test]$ cat a.h 
#ifndef A_H
#define A_H

int a=1;

#endif
[xxx@localhost test]$ cat test.h
#ifndef TEST_H
#define TEST_H

#include"a.h"
void func(int a);

#endif
[xxx@localhost test]$ cat test.c
#include<stdio.h>
#include"test.h"
#include"a.h"

int main()
{
   func(a);

   return 0;
}

void func(int a)
{
   a++;
   printf("a=%d\n",a); 
}
[xxx@localhost test]$ 
#ifndef#define#endif是被用在.h文件中不是.c文件中。test.h包含了a.h ,test.c同时包含了test.h和a.h,那test.c包含了2个a.h,即被重复包含了,这时候就要加上宏。最好2个头文件都要加,正常来说每个头文件都要加上这个宏防止被重复包含。