0

e.g. Is there any difference between these two statements:

extern char a[];
extern char a[4];

What if the real definition of a (in another source file) is

char a[5];

but not

char a[4];
alk
  • 69,737
  • 10
  • 105
  • 255
xiaokaoy
  • 1,608
  • 3
  • 15
  • 27
  • Have a look at http://techblog.rosedu.org/c-extern-internals.html – Mihai Maruseac Aug 14 '13 at 05:32
  • possible duplicate of [C the same global variable defined in different files](http://stackoverflow.com/questions/17800187/c-the-same-global-variable-defined-in-different-files) – jxh Aug 14 '13 at 05:37

3 Answers3

1

extern int a[] declares a to be an array of int with an unspecified size, and is considered an "incomplete type" (C.11 §6.7.6.2 ¶4). An incomplete type is one that for which there is insufficient information to determine its size (C.11 §6.2.5 ¶1). The use of extern means the name has "external linkage" (C.11 §6.2.2 ¶4). All references in the program to the same name with external linkage refer to the same object (C.11 §6.2.2 ¶2).

If you have extern int a[4], but it is defined elsewhere as int a[5], then this will lead to undefined behavior (C.11 §6.2.7 ¶2):

All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

jxh
  • 69,070
  • 8
  • 110
  • 193
0

The following:

extern char a[ ]; // (1)

... means: "go look somewhere for an array of characters called a, it exists.", whereas:

extern char a[ c ]; // (2), where c is some constant.

... means: "go look somewhere for an array of characters of size ( char * c ) called a, it exists.".

Practical examples of both declarations: You should be doing the second declaration if the size of the array is known. If your array is an VLA then it should be declared using the first declaration.

Devolus
  • 21,661
  • 13
  • 66
  • 113
Jacob Pollack
  • 3,703
  • 1
  • 17
  • 39
-2

I've understood, the "extern" statement is just "declaration statement" for the c compiler.

"extern char a[4]"'s "4" is nothing. C compiler doesn't use "4";

Please note the following:

source a : extern char a[4]
source b:  char[5]

gcc 4.6.3 compile result : ok
running result : ok
NREZ
  • 942
  • 9
  • 13
keeptalk
  • 35
  • 2