variable definiton / variable declaration

B

baumann@pan

Hi all,

in a .h header file
i want to declare a var as

extern struct mytype a[200];


after I include the header file in a dot c file


and define the var in the global scope of the dot c file as

struct mytype a[200];

but the compiler complains the redefinition occurs,

how to cope with it? thanks in advance.


baumann at pan
 
B

baumann@pan

btw, the var may be used in other dot c file,

in the h header file, i also tried declare the var as
extern struct mytype *a;

it differs nothing.

I know if in .h file

i declare
extern int a;

in dot c file,
i define
int a = 1;

it would ok, why??

what's difference between the two variables?
 
J

Jens.Toerring

baumann@pan said:
in a .h header file
i want to declare a var as
extern struct mytype a[200];
after I include the header file in a dot c file
and define the var in the global scope of the dot c file as
struct mytype a[200];
but the compiler complains the redefinition occurs,

Are you sure it's the compiler and not the linker?
how to cope with it? thanks in advance.

Having an "extern" declaration of a variable (of whatever type)
in a header file and then defining the variable in one of the
source files is completely legal and has been done by lots of
people in lots of programs. So I suspect your problem is that
you try to define the variable in more than one source file,
i.e. that you have the line

struct mytype a[200];

not only in a single source (.c) file but in two or more. And
that's, of course, something you can't do, because then you have
two or more instances of that variable and the linker won't know
which one you meant with the declaration in the header file.

Regards, Jens
 
C

CBFalconer

baumann@pan said:
in a .h header file
i want to declare a var as

extern struct mytype a[200];

after I include the header file in a dot c file
and define the var in the global scope of the dot c file as

struct mytype a[200];

but the compiler complains the redefinition occurs,

Where have you defined struct mytype?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top