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
?
CodePudding user response:
Some people say that this practice is adopted to avoid repeating declarations.
If some people say that then what they say is misleading. Header guards are used to avoid repeating definitions in order to conform to the One Definition Rule.
CodePudding user response:
Repeating declarations is okay. Repeating definitions is not.
int func(); // declaration
int func(); // declaration; repetition is okay
class X; // declaration
class X; // declaration; repetition is okay
class Y {}; // definition
class Y {}; // definition; repetition is not okay
If a header consists only of declarations it can be included multiple times. But that's inefficient: the compiler has to compile each declaration, determine that it's just a duplicate, and ignore it. And, of course, even if it consists only of declarations at the moment, some future maintainer (including you) will, at some point, change it.
CodePudding user response:
So is it really necessary to avoid repeating declarations?
You can have multiple declarations for a given entity(name). That is you can repeat declarations in a given scope.
is there another reason for using #ifndef?
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).