External Variables

B

Bart C

Suppose I have two modules A and B, and I want them to share the same
variable X.

X might be defined in A but I want to declare it in B as well.

How would I do that in C language?

For functions, I can define it in A and a declaration can be put into a
shared header. But how do I do a declaration of a variable that is defined
elsewhere?

(I can do a workaround using pointers but I'd like direct access)

Thanks, Bart
 
M

Mike Wahler

Bart C said:
Suppose I have two modules A and B, and I want them to share the same
variable X.

X might be defined in A but I want to declare it in B as well.

How would I do that in C language?

For functions, I can define it in A and a declaration can be put into a
shared header. But how do I do a declaration of a variable that is defined
elsewhere?

(I can do a workaround using pointers but I'd like direct access)

Look up 'extern'.

-Mike
 
R

Richard Tobin

Suppose I have two modules A and B, and I want them to share the same
variable X.

X might be defined in A but I want to declare it in B as well.

How would I do that in C language?

For functions, I can define it in A and a declaration can be put into a
shared header. But how do I do a declaration of a variable that is defined
elsewhere?

Exactly the same way. Declare it in the header as "extern whatever X;"

For functions, you don't have to say "extern" (because the absence of
a definition makes it unambiguous), but I generally use it anyway.

-- Richard
 
P

pete

Bart said:
Suppose I have two modules A and B, and I want them to share the same
variable X.

X might be defined in A but I want to declare it in B as well.

How would I do that in C language?

/* BEGIN a.c */

#include "a.h"

int X;

/* END a.c */



/* BEGIN a.h */

extern int X;

/* END a.h */



/* BEGIN b.c */

#include "a.h"

/* END b.c */
 

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

No members online now.

Forum statistics

Threads
474,170
Messages
2,570,925
Members
47,466
Latest member
DrusillaYa

Latest Threads

Top