Avoiding multiple inclusions of header files.
We sometimes need to #include header
files inside other header files.
byte.h
|
typedef unsigned char Byte; const Byte MIN_BYTE = 0; const Byte MAX_BYTE = 255; |
IPAddress.h
|
#include "byte.h" class IPAddress { public: ... private: Byte
IP[4]; }; |
The
above is equivalent to coding:
typedef unsigned char Byte;
const Byte MIN_BYTE = 0;
const Byte MAX_BYTE = 255;
class IPAddress
{
public:
...
private:
Byte
IP[4];
};
EthernetAddress.h
|
#include "byte.h" class EthernetAddress { public: ... private: Byte
Ethernet[6]; }; |
The
above is equivalent to:
typedef unsigned char Byte;
const Byte MIN_BYTE = 0;
const Byte MAX_BYTE = 255;
class EthernetAddress
{
public:
...
private:
Byte
Ethernet[6];
};
...
but we will get a syntax error (Multiple declarations of Byte) if we #include IPAddress.h AND Ethernet.h in a file:
myApp.cpp
|
#include "IPAddress.h" #include "EthernetAddress.h" ... |
equivalent
to:
typedef unsigned char Byte;
const Byte MIN_BYTE = 0;
const Byte MAX_BYTE = 255;
class IPAddress
{
public:
...
private:
Byte
IP[4];
};
<= redefinition
typedef unsigned char Byte;
const Byte MIN_BYTE = 0;
const Byte MAX_BYTE = 255;
class EthernetAddress
{
public:
...
private:
Byte
Ethernet[6];
};
...
There is a standard coding technique to avoid
multiple inclusions of the same header file.
<= preprocessor directives
#ifndef BYTE_H
#define BYTE_H
typedef unsigned char Byte;
const Byte MIN_BYTE = 0;
const Byte MAX_BYTE = 255;
#endif