extern关键字使用 [英] extern keyword usage

查看:148
本文介绍了extern关键字使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个程序,其中我使用 extern 关键字。我不能理解结果。下面是三个例子:

I have three programs in which I am using extern keyword. I am not able to understand the result. Below are three examples:

示例1:我期望下面的代码会给出编译错误,多个声明 k 。但它工作正常?

Example 1: I was expecting that below code will give compilation error that multiple declaration of k. But it works fine?

int k; //works fine
extern int k = 10;

void main()
{
    cout<<k<<endl;
    getchar();
}



给出错误。为什么?

Example 2: When I am trying to initialize "k" in above example compiler gives error. Why?

int k = 20; //error
extern int k = 10;

void main()
{
    cout<<k<<endl;
    getchar();
}

示例3:在此示例中,我更改了示例1 。当我编译这个代码,我得到错误。为什么?

Example 3: In this example I changed the order of definitions mentioned in example 1. When I compile this code I am getting errors. Why?

extern int k = 10;
int k;   //error

void main()
{
    cout<<k<<endl;
    getchar();
}


推荐答案

/ strong>:您尝试初始化一个全局变量两次,有两个不同的值。这是错误。

Example 2: You are trying to initialize a global variable twice, with two different values. This is the error.

示例3 :首先声明一个 extern 然后在同一个编译单元中定义具有相同名称的变量。这不是可能的。

Example 3: You first declare an extern variable, and then define a variable with the same name in the same compilation unit. This is not possible.

这篇关于extern关键字使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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