簡體   English   中英

命名空間 scope - gcc 與 clang 與 msvc 中的外部

[英]extern in namespace scope - gcc vs clang vs msvc

我用最新的gccclangMSVC測試了下面看似奇怪的代碼示例; clang 和 gcc 都給出鏈接錯誤,但 MSVC 編譯和鏈接沒有任何問題。 哪一個是正確的?

// foo.h
#pragma once

namespace A
{
    class foo
    {
    public:
        foo();
        void print();
    };
}

// foo.cpp
#include <iostream>
#include "foo.h"

int* p = nullptr;

using namespace A;

foo::foo()
{
    p = new int(5);
}

void foo::print()
{
    extern int* p;
    std::cout << *p;
}

#include "foo.h"

int main()
{
    A::foo f;
    f.print();
}

gcc 和 clang:

foo.cpp:(.text+0x35): undefined reference to 'A::p'

GCC 和 Clang 均符合標准。 示例和解釋在標准[basic.namespace]/4中給出:

聲明的封閉命名空間是聲明在詞法上出現的命名空間,除了在其原始命名空間之外重新聲明命名空間成員(例如,在 [namespace.memdef] 中指定的定義)。 這樣的重新聲明具有與原始聲明相同的封閉命名空間。 [ 例子:

namespace Q {
  namespace V {
    void f();                   // enclosing namespaces are the global namespace, Q, and Q​::​V
    class C { void m(); };
  }
  void V::f() {                 // enclosing namespaces are the global namespace, Q, and Q​::​V
    extern void h();            // ... so this declares Q​::​V​::​h
  }
  void V::C::m() {              // enclosing namespaces are the global namespace, Q, and Q​::​V
  }
}

——結束示例]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM