假设我有文件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.
更多推荐
发布评论