C ++外部/多重定义 [英] C++ Extern / Multiple Definitions

查看:91
本文介绍了C ++外部/多重定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用externs与C ++中的Ada接口.这两种实现之间有什么区别?

I am trying to interface to Ada in C++ using externs. What is the difference between these two implementations?

实施A

namespace Ada
{
    extern "C"
    {
        int getNumber();
        int index;
        int value;
    }
}

实施B

namespace Ada
{
    extern "C"
    {
        int getNumber();
    }
    extern "C" int index;
    extern "C" int value;
}

两个实现都可以编译.但是Impl-A无法链接,我得到 index value 的多定义错误.我只是想了解差异.

Both implementations compile just fine. But Impl-A fails to link, I get a multiple definition error for index and value. I'm just trying to understand the differences.

推荐答案

外部"C"仅传达用于外部"C"块中代码的链接约定.该块中的任何内容都将与纯c链接在一起.令人困惑的是,extern int完全不同.这意味着您保证某个地方有一个实际的int命名索引和一个实际的int命名值,但是在这里找不到它们.在您的实现A中,从第二个意义上讲,int实际上不是extern - extern"C"仅表示它们提供了严格的c链接约定.

extern "C" only conveys the linking conventions to use for the code within the extern "C" block. Anything in that block will be linked against as if it were pure c. Confusingly, extern int is totally different. It means that you promise there is an actual int named index and an actual int named value somewhere, but they cannot be found here. In your implementation-A the ints are actually not extern in the second sense - the extern "C" only implies that they provide a strict c linking convention.

相同的关键字,但用途完全不同,这很不幸,因为它会导致类似这样的奇怪问题.混合它们是合法的(显然),但是它们并不能像它们的名字所暗示的那样表现在一起.

Same keyword but totally different uses, which is unfortunate since it leads to weird issues like this. Mixing them is legal (obviously), but they don't behave together the way that their name implies.

编辑

有关C ++标准中定义的外部怪异的真实定义,请参见Charle的回答.

See Charle's response for the true definition of the extern weirdness as defined in the C++ standard.

这篇关于C ++外部/多重定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆