为什么我们需要在C'的extern“关键字,如果文件作用域声明在默认情况下具有外部连接? [英] Why do we need the 'extern' keyword in C if file scope declarations have external linkage by default?

查看:236
本文介绍了为什么我们需要在C'的extern“关键字,如果文件作用域声明在默认情况下具有外部连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,一个变量的任何声明或文件范围内的函数有外部链接,默认即可。 静态的意思是它的内部联动,的extern - 这也许其他地方定义,而不是它有外部联动。

如果是这样,为什么我们需要的extern 关键字?换句话说,之间有什么区别 INT富; 的extern INT富; (文件范围)


解决方案

的extern 关键字主要用于变量声明

。当你向前声明功能,关键字是可选的。

关键字让编译器通过的区分一个全局变量的的向前声明的定义的变量:

 的extern双XYZ; //声明XYZ而不定义它

如果你把这个声明本身,然后使用 XYZ 在code,你会在链接阶段触发一个未定义的符号错误。

 双XYZ; //声明并定义XYZ

如果你把这个声明在头文件中,并从几个C / C ++文件使用它,你会在链接阶段触发一个多重定义的错误。

该解决方案是使用的extern 在头,和的的使用extern中只有一个C或C ++文件。

AFAIK, any declaration of a variable or a function in file scope has external linkage by default. static mean "it has internal linkage", extern -- "it maybe defined elsewhere", not "it has external linkage".

If so, why we need extern keyword? In other words, what is difference between int foo; and extern int foo; (file scope)?

解决方案

The extern keyword is used primarily for variable declarations. When you forward-declare a function, the keyword is optional.

The keyword lets the compiler distinguish a forward declaration of a global variable from a definition of a variable:

extern double xyz; // Declares xyz without defining it

If you keep this declaration by itself and then use xyz in your code, you would trigger an "undefined symbol" error during the linking phase.

double xyz; // Declares and defines xyz

If you keep this declaration in a header file and use it from several C/C++ files, you would trigger a "multiple definitions" error during the linking phase.

The solution is to use extern in the header, and not use extern in exactly one C or C++ file.

这篇关于为什么我们需要在C'的extern“关键字,如果文件作用域声明在默认情况下具有外部连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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