外在的奇怪行为

时间:2012-01-27 13:51:45

标签: c++ linker const extern

  

可能重复:
  const and global

此代码将在c ++中生成错误

// Foo.cpp
const int Foo = 99;

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

许多人给出的原因是全局const有内部范围,它是默认的静态。

对此的解决方案是: -

    //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;
    }

我以前认为extern用于告诉编译器,已经在其他文件中的某处将分配的内存分配给了。 在上面的代码中应用相同的逻辑可以解释这里发生的事情,或者extern在c ++中有不同的含义 enter link description here
还要考虑这个页面,这会破坏我的所有直觉......

1 个答案:

答案 0 :(得分:0)

在CPP中添加了extern ...行,我认为这会破坏下一行的内部链接行为。

// Foo.cpp
extern const int Foo;
const int Foo = 99;

还对Main进行了一些不相关的更正:

// Main.cpp
#include <iostream>
extern const int Foo;
int main()
{
    using namespace std;
    cout << Foo << endl;
    return 0;
}

他们是#include <iostream>using namespace std;

这个答案在理论上没有经过仔细的推理,但对我来说对g ++有用。