Multiple declaration of the same variable struct ok?

Here's the setting:

foo.h:

typedef struct my_struct {
  int a;
} my_struct;

const my_struct my_struct1; 
my_struct my_struct2;

foo.c:

#include "foo.h"
const my_struct my_struct1 = { .a = 1 };
my_struct my_struct2 = { .a = 2 };

main.c:

#include "foo.h"
#include <stdio.h>
int main() {
    printf("%d %d\n", my_struct1.a, my_struct2.a);
    return 0;
}

What when compiling with gcc main.c foo.cprints 1 2. The question is, have I declared several variables with the same name (two sets of structures)?

edit: Thanks for the answer to everyone. I see, I might have asked a somewhat confusing question. Initially, I thought it constmight imply some kind of announcement extern(which does not make sense, I know), so I decided to create one my_struct2. To my great surprise, it still works.

+4
source share
2 answers

In accordance with standard C (6.9.2. Definition of external objects)

1 , .

2 static, . , , , , 0.

, foo.h foo.c

const my_struct my_struct1; 
my_struct my_struct2;

, .

foo.c

const my_struct my_struct1 = { .a = 1 };
my_struct my_struct2 = { .a = 2 };

.

main.c .

J

J.5.11 1 , extern; , , undefined (6.9.2).

, undefined, , J.

extern foo.h, main.c .

, . (6.7 )

3 , ( ) , , typedef , , , 6.7.2.3.

. , .

+2
const my_struct my_struct1; 

my_struct1 constant object my_struct. , , .

my_struct my_struct2;

my_struct2 - my-struc t.

, , 2 , mutiple , 2 , .

0

All Articles