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

在c中编译但在c(gcc)中编译时复杂,第1张

概述我在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中的乘法声明有问题,但在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.cOutput:/tmp/ccbd0ACf.o:(.bss+0x0): multiple deFinition of `var'/tmp/cc8DWeC0.o:(.bss+0x0): first defined herecollect2: ld returned 1 exit status

我的gcc和g版本:

gcc --versiongcc (Ubuntu/linaro 4.6.3-1ubuntu5) 4.6.3copyright (C) 2011 Free Software Foundation,Inc.This is free software; see the source for copying conditions.  There is NOwarranty; not even for MERCHANTABIliTY or fitness FOR A PARTIculaR PURPOSE.g++ --versiong++ (Ubuntu/linaro 4.6.3-1ubuntu5) 4.6.3copyright (C) 2011 Free Software Foundation,Inc.This is free software; see the source for copying conditions.  There is NOwarranty; 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中,静态的使用现在已被弃用并被无名空间名称取代).

总结

以上是内存溢出为你收集整理的在c中编译但在c(gcc)中编译时复杂全部内容,希望文章能够帮你解决在c中编译但在c(gcc)中编译时复杂所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1256002.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存