Should the definition and declaration comply?

In my .h file I have

extern int a[4];

in my .c file i have

int a[10];

Are there any problems with this?

Significance of definition and definition? Wrong?

If I write sizeof(a)in one of the files, what will be the output? Is this behavior undefined?

-4
source share
3 answers

If you include the header file in the source file, the two declarations amust be of the same type as C:

(C11, 6.7p4) "All declarations in the same scope that relate to the same object or function must indicate compatible types."

Even if two ads are in two translation units, they must be of the same type:

(C11, 6.2.7p2) " , , , undefined."

+7

:

extern int a[4];
int a[10];

int main()
{
    return 0;
}

gcc a:

cc -Wall -g -ggdb -pipe -pedantic -std=gnu99    test.c   -o test
test.c:2:5: error: conflicting types for ‘a’
int a[10];
     ^
test.c:1:12: note: previous declaration of ‘a’ was here
extern int a[4];
            ^
+6

Undefined , @ouah, , .

, ( ) (gcc, clang, msvc do)

.h, extern int a[4]; .c, int a[10];, , ( ).

.h , .

sizeof(a) == 10 * sizeof(int) .c, , sizeof(a) == 4 * sizeof(int) , .declaring.

:

foo.c:

#include <stdio.h>

int a[10];

void display();

int main() {
    for(int i=0; i<sizeof(a)/sizeof(a[0]); i++) {
        a[i] = i;
    }
    printf("sizeof(a)=%d\n", sizeof(a));
    display();
    return 0;
}

foo2.c:

#include <stdio.h>

extern int a[4];

void display() {
    printf("sizeof(a)=%d\n", sizeof(a));
    for(int i=0; i<sizeof(a)/sizeof(a[0]); i++) {
        printf(" %2d", a[i]);
    }
    fputs("\n", stdout);
}

+ : cc foo.c foo2.c -o foo:

:

sizeof(a)=40
sizeof(a)=16
  0  1  2  3

commons fortran, , C.


,

, , , , - , .

a , .o( .obj) . -, : C .

, , , Undefined. . :

C- , ... [] , C C- , , - . , C...

[] (, , ), 256- . , , ... , , ... , .

, . , , ( , ). , , .

[The] affirm that the strong semantics of the memory model of the opportunity system (which provides protection against unobtrusive memory) can be maintained without sacrificing the benefits of a low-level language.

(underline mine)

TL / DR: Nothing prevents future compilers from adding size information for arrays inside a module (compiled) and raising an error if they are incompatible. There are currently studies for such functions.

0
source

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


All Articles