开发者

C++ Compiler Implementing Namespace

开发者 https://www.devze.com 2023-03-11 07:05 出处:网络
From the C++ compiler\'s point of view, is namespace just a name decoration convention?I have inspected the g开发者_如何学运维enerated assembly listing and found that everything just looks the same ex

From the C++ compiler's point of view, is namespace just a name decoration convention? I have inspected the g开发者_如何学运维enerated assembly listing and found that everything just looks the same except the identifiers are decorated by the namespace's name.


As you point out, name mangling is part of the story (but the reasons for doing it have more to do with linkers rather than compilers).

However, name mangling is far from the whole story as far as the handling of namespaces in the compiler is concerned. Among other things, the compiler has to be able to figure out unqualified names, which can be non-trivial: see argument-dependent lookup.


As far as I know that's what it is. The desciption can be found under name mangling: http://en.wikipedia.org/wiki/Name_mangling


From the C++ compiler's point of view, is namespace just a name decoration convention?

I think yes. Its just a name decoration at the end.

In order to do that compiler does lots of things. It chooses the correct namespace(s), possibly out of many, when resolving a name.

For example,

namespace X
{
  void f(); //compiler chooses X only when decorating f()
  namespace Y
  {
      void f();  //compiler chooses X and Y when decorating f()
      void g()   //compiler chooses X and Y when decorating g()
      {
          f();    //which f? Compiler decorates it with both X and Y.
          X::f(); //which f? Compiler decorates it with X only.
      }
  }
}


It is no coincidence that the first C++ compiler written by Bjarne Stroustrup was called CFront. It converted C++ code to C and fed it to a C compiler. So, I believe it is just name mangling to create unique symbols for overloading & avoid name conflicts (namespace)

0

精彩评论

暂无评论...
验证码 换一张
取 消