变量声明冲突的编译器错误:“与带有'C'链接的新声明冲突". [英] Compiler error for conflicting variable declarations: "conflicts with new declaration with 'C' linkage"

查看:1665
本文介绍了变量声明冲突的编译器错误:“与带有'C'链接的新声明冲突".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些无法在较新的编译器上构建的旧代码.简单的例子:

I ran across some legacy code that's failing to build on a newer compiler. The boiled down example:

int x;
extern "C" { int x }; // conflicts with C++ linkage above
// note: without the braces it would've been equivalent to:
// extern "C" { extern int x; }
//
// for reference, see the notes section here:
//   http://en.cppreference.com/w/cpp/language/language_linkage#notes

较早的编译器没有对其进行标记,但是gcc(从4.1.2开始)和clang都对其进行了标记.

The older compilers weren't flagging it, but both gcc (as of 4.1.2) and clang flag it.

C语的输出:

error: declaration of 'x' has different language linkage

GCC的输出:

error: previous declaration of 'int x' with 'C++' linkage
error: conflicts with new declaration with 'C' linkage

这让我感到惊讶,因为编译器没有以任何特殊方式处理x,据我所知,除调试信息外,目标文件没有其他区别(基于我对objdump/readelf的浅浅测试) )

This surprised me because the compiler doesn't mangle x in any special way, and as far as I can tell nothing is different about the object file other than debug information (based on my admittedly shallow test with objdump/readelf)

我的问题:如果没有功能上的区别,这为什么会出错?

My question: why is this an error if there's no functional difference?

顺便说一句,我并不反对更改代码.我想知道是否还有其他事情发生,而不仅仅是标准说这是不正确的".

As an aside, I'm not averse to changing the code; I wanted to know whether there was something more going on than just "the standard says this is ill formed".

推荐答案

我浏览了各个* stack站点,并在该主题上发现了与链接规范相互冲突的功能相关的问题.

I looked through the various *stack sites and mostly found questions on this topic relating to functions with conflicting linkage specifications.

我在 gcc bugzilla数据库中找到了我的[第一个]答案:

该标准在7.5/5中说:如果同一函数或对象的两个声明指定了不同的链接规范,则这些声明出现在同一翻译单元中,则程序将格式错误. ]".这就是为什么现在拒绝注释6中的代码的原因.

The standard says in 7.5/5: "If two declarations of the same function or object specify different linkage-specifications [...] the program is ill-formed if the declarations appear in the same translation unit [...]". That is why code like that in comment 6 is now rejected.

我的假设是否正确(关于POD变量的C/C ++链接之间的功能差异)是否正确,看来该错误是为了防止不良样式.

Whether my supposition is correct (about the functional difference between C/C++ linkage for POD variables) or not, it appears the error is intended to prevent bad style.

然后,我发现了这篇有关存储类说明符的文章,其中一篇有关语言链接.在那些文章中,我没有发现任何与到目前为止所学内容相抵触的东西.第二个人说:

Then I found this article about storage class specifiers and one about language linkage. I didn't see anything in those articles conflicting with what I've learned so far; the 2nd one says:

同样,同一名称空间中的两个变量不能具有两种不同的语言链接.

Likewise, two variables in the same namespace cannot have two different language linkages.

这篇关于变量声明冲突的编译器错误:“与带有'C'链接的新声明冲突".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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