为什么我可以在包含const int且没有编译器错误的多个cpp文件中包含头文件?(Why is it that I can include a header file in multiple cpp

编程入门 行业动态 更新时间:2024-10-28 18:30:35
为什么我可以在包含const int且没有编译器错误的多个cpp文件中包含头文件?(Why is it that I can include a header file in multiple cpp files that contains const int and not have a compiler error?)

假设我有文件a.cpp b.cpp和文件ch两个cpp文件都包含ch文件。 头文件包含一堆const int定义,当我编译它们时,我没有错误,但我可以访问这些const,就像它们是全局变量一样。 所以,如果我有多个const定义以及这些const int具有类似全局的作用域,为什么我没有得到任何编译错误?

Let's assume that I have files a.cpp b.cpp and file c.h. Both of the cpp files include the c.h file. The header file contains a bunch of const int definitions and when I compile them I get no errors and yet I can access those const as if they were global variables. So the question, why don't I get any compilation errors if I have multiple const definitions as well as these const int's having global-like scope?

最满意答案

这是因为命名空间范围内的const声明意味着内部链接。 具有内部链接的对象仅在定义它的翻译单元中可用。 所以从某种意义上说,你在ch拥有的一个const对象实际上是两个不同的对象,一个是a.cpp内部对象,另一个是a.cpp内部b.cpp 。

换一种说法,

const int x = ...;

相当于

static const int x = ...;

int x;

类似于

extern int x;

因为命名空间范围内的非const声明意味着外部链接。 (在最后一种情况下,它们实际上并不等同, extern以及明确指定外部链接的对象都会产生声明 ,而不是定义 。)

请注意,这是特定于C ++的。 在C中, const不会改变隐含的链接。 原因是C ++委员会希望你能够写作

const int x = 5;

在标题中。 在C中,包含在多个文件中的头文件会导致链接器错误,因为你会多次定义同一个对象。

This is because a const declaration at namespace scope implies internal linkage. An object with internal linkage is only available within the translation unit in which it is defined. So in a sense, the one const object you have in c.h is actually two different objects, one internal to a.cpp and one internal to b.cpp.

In other words,

const int x = ...;

is equivalent to

static const int x = ...;

while

int x;

is similar to

extern int x;

because non-const declarations at namespace scope imply external linkage. (In this last case, they aren't actually equivalent. extern, as well as explicitly specifying external linkage, produces a declaration, not a definition, of an object.)

Note that this is specific to C++. In C, const doesn't change the implied linkage. The reason for this is that the C++ committee wanted you to be able to write

const int x = 5;

in a header. In C, that header included from multiple files would cause linker errors, because you'd be defining the same object multiple times.

更多推荐

本文发布于:2023-04-29 09:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335842.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   编译器   头文件   错误   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!