0

In a header file functions.h, the first two statements are defining FUNCTIONS_H if not already defined. Can someone explain the reason for this action?

#ifndef FUNCTIONS_H 
#define FUNCTIONS_H 

void print(); 
int factorial(int); 
int multiply(int, int); 

#endif 
Learner
  • 85
  • 2
  • 10

2 Answers2

2

The article you linked isn't about Makefiles at all, it's about compiling multi source file code.

Those are so called include guards. They prevent code from being included unnecessarily multiple times.

If FUNCTIONS_H is not defined then include the content of the file and define this macro. Otherwise, it's defined so file was already included.

There is also #pragma once serving the very same purpose, which although not being in the standard, is supported by many major compilers.

Consider example:

There are also two next header files - func1.h and func2.h. Both have #include "functions.h" inside.

If in main.cpp we do:

#include "func1.h"
#include "func2.h"

// rest of main...

The code will preprocessed to:

#include "functions.h"
// rest of func1.h

#include "functions.h"
// rest of func2.h

// main...

Then:

#ifndef FUNCTIONS_H 
#define FUNCTIONS_H 

void print(); 
int factorial(int); 
int multiply(int, int); 

#endif 
// rest of func1.h


#ifndef FUNCTIONS_H 
#define FUNCTIONS_H 

void print(); 
int factorial(int); 
int multiply(int, int); 

#endif 
// rest of func2.h

// main...

As you can see if not for include guards, the prototypes for functions would appear for second time. There could be also other crucial things, which redefinition would be causing errors.

Jorengarenar
  • 2,705
  • 5
  • 23
  • 60
1

It's an "include guard". It prevents redefinition if the header file is #included multiple times.

It's a C++ thing. It has nothing to do with makefiles.

jkb
  • 2,376
  • 1
  • 9
  • 12