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"
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
{
};