Is UB declaring the same array as extern with different sizes in different compilation units

This is mainly a sequel. If matching definitions and declarations?

Question

Is it legal in C to have (for example) int a[10];in one compilation unit and extern int a[4];in another?

(You can find a working example in my answer to answer the question)


Denial of responsibility:

  • I know this is dangerous and will not do it in production code.
  • I know that if you have both in the same compilation unit (usually by including the .h file in the file containing the definition), the compilers will detect an error
  • I already read the "Reply How to use extern to exchange variables between source files? but couldn’t find the answer to this particular moment - even if Jonathan showed even worse habits ...

Even if different comments in the link mail noticed that as UB I could not find any authoritative help. Therefore, I would say that there is no UB, and the second compilation module will have access to the beginning of the array, but I would really like to receive confirmation - or instead, a link about why it is UB

+4
source share
2 answers

This behavior is undefined.

Section 6.2.7.2 of the C99 states:

All declarations related to the same object or function must be of a compatible type; otherwise, the behavior is undefined.

. , [...] [...], 6.2.2:

, , .

, 6.7.5.2.4 C99 , , :

, , , , , . , undefined, .

( )

, 1D-, , , , , , , sizeof ( -).

, , .

+6

, . .

undefined, extern , .

, "" , . ( ).

-1

Source: https://habr.com/ru/post/1598378/


All Articles