用C的extern的行为 [英] Behaviour of extern in C

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

问题描述

如果我宣布 int数组[10]; 在file1.c中

If I declare int Array[10]; in file1.c

在file2.c中,如果我我有这样的功能。

In file2.c if I I have a function like this

extern int *Array;
fun()
{
    Array[0]=10; 
}

是否有与此不?

推荐答案

是有问题。

您声明阵列是一个指针,而取而代之的则是一个阵列。这两个非常不同的对象,并在这里你基本上编译器提供虚假信息。

You are declaring a Array to be a pointer, while instead it's an array. The two are very distinct objects and here you're basically providing false information to the compiler.

请注意,在C语法来访问一个元素是数组[0] 在这两种情况下,但是,如果阵列是一个指针变量所需的机器code将不同于如果阵列是不是数组(与指针有一个额外的间接)。

Note that the C syntax to access an element is Array[0] in both cases, but if Array is a pointer variable the machine code needed will be different from if Array is instead an array (with the pointer there is one extra indirection).

例如,如果数组1 声明为的extern为int *阵列按<$产生机器code C $ C>数组1 [九] + = 3 是:

For example if Array1 is declared as extern int *Array the machine code generated by Array1[ix] += 3 by gcc is:

movslq  ix(%rip), %rax        ;; Load index value from location ix
movq    Array1(%rip), %rdx    ;; Load pointer value from location Array1
leaq    (%rdx,%rax,4), %rax   ;; Compute rax as pointer + index*4
addl    $3, (%rax)            ;; Add 3 to the location pointed by rax

如果不是 ARRAY2 声明为的extern INT ARRAY2 [10] 的code为 ARRAY2 [九] + = 3 很简单:

If instead Array2 is declared as extern int Array2[10] the code for Array2[ix] += 3 is simply:

movslq  ix(%rip), %rax        ;; Load in rax the index value from location ix
addl    $3, Array2(,%rax,4)   ;; Add 3 to the location Array2 + index*4

正如你在有一个额外的间接和内存地址的内容数组1 读寻找到增量应在内存中完成第一种情况看。在第二种情况下,而不是只需要索引被读取以计算,其中递增的位置将是

As you can see in the first case there is an extra indirection and the content of the memory at address Array1 is read to find where the increment should be done in memory. In the second case instead only the index needs to be read to compute where the location to increment will be.

为了让事情在C的混乱数组衰变成指针在许多情况下的第一要素,因此,例如,如果你已经一个函数期待一个指针传递数组是好的,因为编译器会照顾处理的差。

To make things more confusing in C an array "decays" into a pointer to the first element in many cases, so for example if you've a function expecting a pointer passing an array is fine because the compiler will take care of handling the difference.

如果在内存中对象是一个数组或一个指针,因为语义不同编译器必须被告知;在问题code,而不是不正是这...计划的一部分分配一个数组,并告诉它是一个指针,而不是程序的某些部分。

The compiler must be told if an object in memory is an array or a pointer because the semantic is different; the code in the question instead does exactly this... one part of the program allocates an array and tells some part of the program that it's a pointer instead.

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

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