简体   繁体   English

为什么要避免C++中的冗余声明?

[英]Why should avoid redundant declarations in C++?

I am learning multiple file compilation in C++ and found practice like this:我在C++学习多文件编译,发现有这样的做法:

#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).但我尝试声明 function 两次,代码运行良好,没有任何编译错误(如下所示)。

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 ?或者还有其他使用#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. Header 守卫用于避免重复定义,以符合单一定义规则。

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.如果 header 仅包含声明,则可以多次包含它。 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.也就是说,您可以在给定的 scope 中重复声明。

is there another reason for using #ifndef?使用#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.使用header 守卫的主要原因是确保header 文件第二次被#included时,其内容被丢弃,从而避免重复定义class、内联实体、模板等,它可能包含。

In other words, so that the program conform to the One Definition Rule (aka ODR).换句话说,使程序符合单一定义规则(又名 ODR)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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