本文介绍了常量和全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码会在c ++中产生错误

  // Foo.cpp 
const int Foo = 99;

// Main.cpp
extern const int Foo;
int main()
{
cout<< Foo<< ENDL;
返回0;





$ b

许多人给出的理由是全局的const有内部的作用域,它是默认的静态的。

解决方案是: -
$ b $ pre $ //Foo.h
extern const int Foo;

// Foo.cpp
#includeFoo.h
const int Foo = 99;

// Main.cpp
#includeFoo.h
int main()
{
cout<< Foo<< ENDL;
}

我以前认为extern是用来告诉编译器内存是否为indentifer已被分配到其他文件的某处。

在上面的代码中应用相同的逻辑,任何人都可以解释这里发生了什么,或者extern在c ++中有不同的含义??



也可以考虑这页是破坏我所有的直觉。

解决方案

如果我们必须声明一个全局常量静态)? extern 如何提供帮助?
$ b

A const 使用 extern 限定符声明的c $ c>对象具有外部链接。

所以如果你想使用 const 跨越多个翻译单元,为其添加一个 extern 限定符。



默认情况下全局变量具有外部链接,为什么默认情况下const全局链接具有内部链接?

参考:

C ++ 03标准附录C兼容性C.1.2第3条:基本概念






遵循一个简单规则避免混淆:



默认情况下,链接对于非常量符号是外部的,对于常量符号是静态(内部)。


This code will produce error in c++

// Foo.cpp
const int Foo = 99;

// Main.cpp
extern const int Foo;
int main()
{
    cout << Foo << endl;
    return 0;
}

Reason as given by many is global const has internal scope and it is default static.

solution to this is :-

    //Foo.h
    extern const int Foo;

    // Foo.cpp
    #include "Foo.h"
    const int Foo = 99;

    // Main.cpp
    #include "Foo.h"
    int main()
    {
       cout << Foo << endl;
    }

I used to think that extern is used to tell compiler that memory for the indentifer is already allocated somewhere in other files.
Applying same logic on above code can anyone explain what is happening here or extern has different meaning in c++??
enter link description here
Also consider this page it is spoiling my all intuitions..

解决方案

What if we have to declare only a global constant(not static)? How extern help in doing this?

A const object declared with extern qualifier has external linkage.
So if you want to use a const across multiple Translation units, add an extern qualifier to it.

While a global variable has external linkage by default,why a const global has internal linkage by default?

Reference:
C++03 Standard Annex C Compatibility C.1.2 Clause 3: basic concepts


Avoid the confusion by following a simple rule:

By default Linkage is external for non-const symbols and static (internal) for const symbols.

这篇关于常量和全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:37