Using an external variable in C

When I went through the concept of a variable extern, I came across this snippet:

int array[10]; // in file1.c
extern int *array; // in file2.c

The explanation was as follows: the semantics of the array are different in two files. The component cannot resolve the name and at the same time will not mark an error, but the programs do not work at run time.

But when I tried it, neither it failed at runtime, did not even receive any warnings.

My doubt is whether I can use any semantics, and when used it externmeans that if my external variable is of type int, can the other variable be a pointer or an array of type !!!

Will it be right, can someone explain this to me?

+3
source share
5 answers

. , Jens Gustedt .

, , .

int array[10];      // in file1.c
extern int *array;  // in file2.c

, , , . , . , :

int array[10];

array[0], , array, 0x20132014. 0 array[0] 0x20132014;

:

int *p;

, , , p. . , p[0], . p, 0x12345678, p, 0x12345678. , 0x10101010, , p ( p[0]). 0x10101010, p[0].

, , , :

2 array[0] . array , array , , , array[0], , array[0], . , , .

, . , .

+2

, , undefined. , :

int array[10]; // in file1.c
extern int array[]; // in file2.c

file2.c. , , sizeof array.

+1

, . undefined , array file2.c.

file1.c array array 10 int s. file2.c array int *. , , array file2.c file1.c. , , , .

array file2.c, , , .

// in file2.c
// may cause seg fault

int x = *array;

// in file2.c
// sizeof may not be applied to array in this scope
// because array is incomplete type until linked.

extern int array[];

. . , . , .

, - , , . . .

+1

, array int [10], int *.

int array[10];        // in file1.c
extern int array[10]; // in file2.c
0

this.extern . . , , int.In - .

file1.c - int 10.

file2.c - , none 1.

I use gdb for testing.

an array in file2.c is

(gdb) p array
$2 = (int *) 0x0
(gdb) p &array
$3 = (int **) 0x804a040

I set the numbers for the array.

(gdb) x/10 &array
0x804a040 <array>:  0   1   2   3
0x804a050 <array+16>:   4   5   6   7
0x804a060 <array+32>:   8   9

to access the array in file2.c you need an array of fills for int * type

(gdb) p/d ((int*)&array)[9]
$8 = 9

in the file1.c array is a normal array.

(gdb) p array[2]
$11 = 2

note that you cannot use the array in file2.c as you do in file1.c. You will get a segmentation error.

0
source

All Articles