LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   how #ifndef in header file works for multiple inclusion? (https://www.linuxquestions.org/questions/programming-9/how-ifndef-in-header-file-works-for-multiple-inclusion-4175420778/)

mnowhere 08-07-2012 02:40 AM

how #ifndef in header file works for multiple inclusion?
 
I have a header file with following contents,

Code:

#ifndef __MY_HEADER_
#defeine __MY_HEADER_

<..........header content......>

#endif

As per my understanding first time when the preprocessor includes this header in some .c file it checks if __MY_HEADER_ is defined, since its not defined it will include the following code into the .c file along with defining __MY_HEADER_.

my doubt is, when I include this header in another .c file, how would it takes __MY_HEADER_ definition. According to me, as __MY_HEADER_ is already defined the contents of the header file should not be included in any further .c files.

Please clarify me about this.

Wim Sturkenboom 08-07-2012 03:05 AM

No, the pre-processor does not know about __MY_HEADER_ in the other C-files; the pre-processor works on a single file (and the files that are included in that file) at a time.

mnowhere 08-07-2012 03:23 AM

Hi Wim Sturkenboom,

So you mean that the, "#ifndef __MY_HEADER_ #define __MY_HEADER_" is applied for every file freshly?
I mean the macro __MY_HEADER_ is kind of local to each .c files which includes the header file "my_header.h" (the header file containing the above mentioned code snippet)?

Wim Sturkenboom 08-07-2012 05:23 AM

Yes, that's what I mean.

colucix 08-07-2012 09:05 AM

Moved: This thread is more suitable in Programming and has been moved accordingly to help your thread/question get the exposure it deserves.

theNbomr 08-08-2012 09:57 AM

This construct is used when you have a lot interdependence between modules in a project. As an example, you may have a project with 3 C source files (this.c, that.c, theOther.c). Each C source file has a corresponding header file (this.h, that.h, theOther.h) which is #included in the .c source file.
In this.h, you could then have
Code:

#ifndef THIS_H
#define THIS_H

#include "that.h"
#include "theOther.h"

//...  Other declarations, etc. here
#endif

And in that.h, you could have
Code:

#ifndef THAT_H
#define THAT_H

#include "this.h"
#include "theOther.h"

//...  Other declarations, etc. here
#endif

Notice that without the conditionals, there would be a circular reference (this refers to that, which refers to this...), which would be a Bad Thing.

--- rod.


All times are GMT -5. The time now is 05:56 PM.