-2

I am new in embedded code and I'm reading an example code of NXP, this example is written for FRDM-KL25Z. And in file main.h, I do not know the line:

#ifndef MAIN_H_ #define MAIN_H_ #endif /* MAIN_H_ */ 

is using for what? I think maybe it defines the name for main.h is MAIN_H_ ? But the purpose of this define is what? And in file main.c, it still include main.h as below:

#include "main.h" 
1
  • It is not specific to embedded code, you need include guards in any C or C++ code. Most modern compilers support #pragma once as an alternative. Commented Nov 7, 2019 at 22:18

1 Answer 1

1

Let's imagine I have a header file like so:

// foo.h struct Foo { }; 

And then I accidentally include it twice:

#include "foo.h" #include "foo.h" 

This would end up attempting to compile the following, which would generate an error...

struct Foo { }; struct Foo //< error 'Foo' declared twice { }; 

One way to fix this is to get the pre-processor to remove the second occurance, and to do this we define a unique identifer per header file. e.g.

#ifndef FOO_H_ #define FOO_H_ struct Foo { }; #endif 

And now if we accidentally include it twice...

#ifndef FOO_H_ //< not yet declared #define FOO_H_ //< so declare it struct Foo { }; #endif #ifndef FOO_H_ //< this time FOO_H is defined... #define FOO_H_ //< ... so DO NOT include this code. struct Foo { }; #endif 

Personally though I'd recommend achieving this same thing via the slighty non-standard (although supported by most, if not all, compilers).

#pragma once //< only ever include this file once struct Foo { }; 
Sign up to request clarification or add additional context in comments.

4 Comments

thank you so much. Now i am unstanding the purpose of the pre-processor FOO_H_ is avoiding case i include file.h more than once. So in main.h, can i write include FOO_H_ instead of foo.h ?
Given the question is tagged C, examples in C++ are probably inappropriate.
@ThanhNguyen No, that make no sense. This example is also rather simplistic. The more likely scenario is where you have two different include files that each nest-include a common header.
'#praga once’ ? Typo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.