#ifndef 的作用

这个问题之前感觉比较懂了;其实还是比较糊涂的,今天又搞了一次。

百度上的解释: http://baike.baidu.com/view/1617265.htm
在c语言中,对同一个变量或者函数进行多次声明是不会报错的。所以如果h文件里只是进行了声明工作,即使不使用# ifndef宏定义,多个c文件包含同一个h文件也不会报错。
  但是在c++语言中,#ifdef的作用域只是在单个文件中。所以如果h文件里定义了全局变量,即使采用#ifdef宏定义,多个c文件包含同一个h文件还是会出现全局变量重定义的错误。
  使用#ifndef可以避免下面这种错误:如果在h文件中定义了全局变量,一个c文件包含同一个h文件多次,如果不加#ifndef宏定义,会出现变量重复定义的错误;如果加了#ifndef,则不会出现这种错误。

自己写了程序测试:源文件有3个,tst.h tst1.cpp tst2.cpp
其中 tst.h:
#ifndef TST_H
#define TST_H
int g_a;
#endif
tst1.cpp:
#include "tst.h"

void test()
{
    g_a++;
    cout << g_a << endl;
}
tst2.cpp:
#include "tst.h"
#include
using std::cout;
using std::endl;
extern void test();

int main()
{
    //test();
    cout << g_a << endl;
}
敲入命令:g++ *.cpp -o tst
结果出现:
/tmp/ccAoniTc.o:(.bss+0x0): multiple definition of `g_a'
/tmp/ccuwNBya.o:(.bss+0x0): first defined here
意思就是说 g_a重复定义了;一时间傻眼儿了,不是加过了 "ifndef TST_H"了吗?这难道不能避免重复编译和重复定义?
网上的解释是这样:各个源文件的解释(个人感觉应该是编译)是独立进行的,所以 TST_H 并没在二次编译的时候识别出来。
那 ifndef 还有什么用呢?它怎么避免头文件多次被include的时候,避免重复编译和重复定义呢?本人试了一下,这个时候它是有用的:源文件 tst.h tst3.cpp
tst.h:
#ifndef TST_H
#define TST_H
int g_a;
#endif
tst3.cpp:
#include "tst.h"
#include "tst.h"
#include
using std::cout;
using std::endl;
extern void test();

int main()
{
    //test();
    cout << g_a << endl;
}
注意tst3.cpp中有2个#include "tst.h", 这个时候如果tst.h中没有#ifndef的话,编译就会出错了:
tst.h:3: error: redefinition of ‘int g_a’
tst.h:3: error: ‘int g_a’ previously declared here
当然你会说谁会犯这么低级的错误呢?把一个头文件同时include两次;但是项目大,头文件架构组织不清
的时候就有可能出现这种情况。
当然,可能#ifndef不止有这个作用,哪天碰到了继续研究吧。

你可能感兴趣的:(#ifndef 的作用)