I am learning multiple file compilation in C++ and found practice like this:
#ifndef MY_LIB_H
#define MY_LIB_H
void func(int a, int b);
#endif
Some people say that this practice is adopted to avoid repeating declarations. But I try to declare a function twice and the code just runs well without any compilation error (like below).
int func();
int func();
int func()
{
return 1;
}
So is it really necessary to avoid repeating declarations? Or is there another reason for using #ifndef
?
You can have multiple declarations for a given entity(name). That is you can repeat declarations in a given scope.
The main reason for using header guards is to ensure that the second time a header file is
#included
, its contents are discarded, thereby avoiding the duplicate definition of a class, inline entity, template, and so on, that it may contain.In other words, so that the program conform to the One Definition Rule(aka ODR).