-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"
Ramprasath Selvam
  • 3,868
  • 3
  • 25
  • 41
Thanh Nguyen
  • 45
  • 1
  • 7
  • 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. – Clifford Nov 07 '19 at 22:18

1 Answers1

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 
{
};
robthebloke
  • 9,331
  • 9
  • 12
  • 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 ? – Thanh Nguyen Nov 07 '19 at 06:48
  • Given the question is tagged C, examples in C++ are probably inappropriate. – Clifford Nov 07 '19 at 22:12
  • @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. – Clifford Nov 07 '19 at 22:16
  • '#praga once’ ? Typo. – Clifford Nov 07 '19 at 22:19