命名空间对 c++ 有何影响? 与 c 中的链接相比?

发布于 2024-07-14 22:26:42 字数 86 浏览 6 评论 0原文

与 c 中的链接相比,c++ 链接中的命名空间有何影响?

是否可以仅通过使用命名空间来创建一个具有内部链接到外部链接的名称。反过来也类似。

What is the impact of namespaces in c++ linkages compared to linkages in c?

Is it possible to make a name that has internal linkage to external linkage just by using namespace.Similarly the other way around.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倾城泪 2024-07-21 22:26:42

一般来说,在名称被破坏并进入链接器之前,名称空间名称会被添加到任何封闭实体的名称之前。

如果您有两个函数在不同的命名空间中具有相同的签名,那么它们可以很好地链接到一个文件中。 如果您有两个具有相同名称的类和至少一个具有相同签名的方法,并且这些类位于不同的命名空间中,那么它们再次链接在一起就可以了。

In general, namespace name is prepended to any enclosed entity's name before the name is mangled and goes to the linker.

If you have two functions with the same signatures in different namespaces they link into one file just fine. If you have two classes with the same name and at least one method with the same signature and these classes are in different namespaces – they again link together just fine.

离笑几人歌 2024-07-21 22:26:42

C 和 C++ 都允许对象和函数具有静态文件链接,也称为内部链接。 C++ 支持使用未命名的命名空间来代替文件作用域,这是编译器的一个好处。 static 是一个链接修饰符。 因此,如果您想要文件作用域和内部链接,则应该在 C++ 中同时使用命名空间和静态。 然而,在 C 中,您只需要 static 关键字即可实现相同的效果。

/* C and C++ code */

static int  bufsize = 1024;
static int  counter = 0;

static long square(long x)
{
    return (x * x);
}

在 C++ 中执行此操作的首选方法:

 // C++ code
namespace /*unnamed*/
{
    static int  bufsize = 1024;
    static int  counter = 0;

    static long square(long x)
    {
        return (x * x);
    } 

}

Both C and C++ allow objects and functions to have static file linkage, also known as internal linkage. C++, supports the use of unnamed namespaces instead for file scope, which is a compiler benefit. static is a linkage modifier. So, if you want file scope and internal linkage, you should use both namespace and static in C++. In C, however, you only need static keyword to achieve the same.

/* C and C++ code */

static int  bufsize = 1024;
static int  counter = 0;

static long square(long x)
{
    return (x * x);
}

The preferred way of doing this in C++:

 // C++ code
namespace /*unnamed*/
{
    static int  bufsize = 1024;
    static int  counter = 0;

    static long square(long x)
    {
        return (x * x);
    } 

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文