define,ifndef,endif傻傻分不清

一、无论 某头文件 是否被 多个文件引用,都要加上#ifndef #endif。

试想:

        有2个.c文件,都#include引用了 同一个.h文件;

        编译时,两个.c文件 都要 一同编译 成一个 可运行文件;

        那么会产生 声明冲突。

        

#idndef HAPPY_H //防止HAPPY_H被重复引用、重复编译

#define HAPPY_H
...

#endif

举例:

        某工程,有4个文件,dog.cpp  dog.h  aa.h bb.h

dog.cpp内容如下:

#include aa.h
#include bb.h
aa.h和bb.h内容如下:

#include dog.h

  

dog.h内容如下

class Dog {
    ..
}

      我们发现:

                dog.cpp头文件包含了aa.h bb.h

                aa.h bb.h头文件又包含了dog.h

                而dog.h又有class dog的定义

        编译运行:

                编译器 编译 dog.cpp时,先根据头文件,去编译 aa.h, 再根据aa里面的#include dog.h去编译dog.h文件,这样就把dog.h里面的class dog编译了;

                然后再根据dog.cpp的第二句#include“bb.h”,去编译bb.h,再根据bb里面的#include dog.h去编译dog.h,但是之前class dog已经编译过了,所以会报 重定义 错误!

        所以:

                加上#ifndef #endif很重要,看来是每个文件都要加上。。

二、ifdef

描述:条件编译

#ifdef macro_definition

 macro_definition为: 预处理器 定义的 宏,以将c源代码包含到已编译的应用程序中。

注意:必须由#endif 指令关闭

/* Example using #ifdef directive for inserting platform specific source code by TechOnTheNet.com */
 
#include <stdio.h>
 
#define UNIX 1
 
int main()
{
   #ifdef UNIX
   printf("UNIX specific function calls go here.\n");
   #endif
 
   printf("TechOnTheNet is over 10 years old.\n");
 
   return 0;
}

cad44c1c229e47309faf68f96e88f337.png输出,例中启动了UNIX源代码,若要禁用UNIX源代码,请将改行更改为#undef UNIX