加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在c中编译但在c(gcc)中编译时复杂

发布时间:2020-12-16 03:28:08 所属栏目:百科 来源:网络整理
导读:我在c中的乘法声明有问题,但在c中没有. 您可以查看代码以获取更多信息. 文件main.c #ifndef VAR#define VARint var;#endifint main(){} 文件other.c #ifndef VAR#define VARint var;#endif 用gcc编译 gcc main.c other.c success 用g编译 g++ main.c other.c
我在c中的乘法声明有问题,但在c中没有.
您可以查看代码以获取更多信息.

文件main.c

#ifndef VAR
#define VAR
int var;
#endif
int main(){}

文件other.c

#ifndef VAR
#define VAR
int var;
#endif

用gcc编译

gcc main.c other.c
>> success

用g编译

g++ main.c other.c
Output:
/tmp/ccbd0ACf.o:(.bss+0x0): multiple definition of `var'
/tmp/cc8dweC0.o:(.bss+0x0): first defined here
collect2: ld returned 1 exit status

我的gcc和g版本:

gcc --version
gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation,Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

g++ --version
g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
Copyright (C) 2011 Free Software Foundation,Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

解决方法

由于变量var的多个定义,您的代码在C和C中都是正式错误的.只是这种类型的错误传统上被C编译器忽略为一种流行的非标准扩展.在C语言规范中甚至提到了这个扩展

J.5 Common extensions

The following extensions are widely used in many systems,but are not portable to all
implementations. […]

J.5.11 Multiple external definitions

There may be more than one external definition for the identifier of an object,with or
without the explicit use of the keyword extern; if the definitions disagree,or more than
one is initialized,the behavior is undefined (6.9.2).

但从形式上讲,C和C语言中的多重定义错误完全相同.让你的C编译器表现得更迂腐(如果它有一个选项,禁用扩展),你的C编译器也应该生成与C编译器完全相同的错误.

同样,您的代码包含变量var的多个定义,这在C和C中都是错误的.你的#ifdef指令根本没有解决任何问题. Preperocessor指令在这里无法帮助你.预处理器在每个翻译单元中本地和独立地工作.它无法跨翻译单位看到.

如果要创建全局变量(即所有翻译单元共享的同一变量),则需要对该变量进行一个且仅一个定义

int var;

在一个且只有一个翻译单元.所有其他翻译单元应接收var的非定义声明

extern int var;

后者通常放在头文件中.

如果您需要在每个翻译单元中使用独立的变量var,只需在每个翻译单元中将其定义为

static int var;

(尽管在C中,静态的使用现在已被弃用并被无名空间名称取代).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读