简体   繁体   中英

Why should avoid redundant declarations in C++?

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 ?

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.

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM