C&安培; C ++默认的全局变量联动,多申报和放大器;定义问题 [英] c & c++ default global variable linkage, multiple declaration & definition problem

查看:165
本文介绍了C&安培; C ++默认的全局变量联动,多申报和放大器;定义问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

code1.c /的.cpp

int a;

// ... and so on

code2.c /的.cpp

int a;

int main(void) {
    return 0;
}

去编译:

$gcc code1.c code2.c      # this is fine
$

$g++ code1.cpp code2.cpp  # this is dead
/tmp/ccLY66HQ.o:(.bss+0x0): multiple definition of `a'
/tmp/ccnIOmPC.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status

有C&放大器之间的任何全局变量联动差异; C ++?

Is there any global variable linkage difference between C & C++?

推荐答案

这不是严格的法律。 int类型的; 是C的暂定定义你被允许多个暂定定义,并在每次使用C外部链接每个对象的转换单元最多有一个非试探性的定义,但在所有翻译单元只有一个定义的程序。

It's not strictly legal. int a; is a tentative definition in C. You are allowed multiple tentative definitions and at most one non-tentative definition per translation unit of each object with external linkage in C, but only one definition across all translation units in a program.

这是普遍采用的扩展,允许跨越多个翻译单元的暂定定义用C,只要不超过一个翻译单元包含一个非试探性的定义,但它不是严格的标准。

It is a commonly implemented extension to allow tentative definitions across multiple translation units in C so long as not more than one translation unit contains a non-tentative definition, but it's not strictly standard.

在C ++ int类型的; 只是一个定义 - 有没有初步的概念 - 它仍然是非法的整个程序的翻译单元对象的多个定义

In C++ int a; is just a definition - there's no concept of tentative - and it's still illegal to have multiple definitions of an object across the translation units of a program.

对于C的情况下,你不妨看看<一个href=\"http://stackoverflow.com/questions/4990315/why-a-variable-cant-be-defined-twice-in-2-files-in-c\">this问题。

For the C case, you may wish to look at this question.

这篇关于C&安培; C ++默认的全局变量联动,多申报和放大器;定义问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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