Global Variables

N

noridotjabi

I know that if I want a variable to be global I can define it as such:

....

int var;

int main() {

....

return 0;
}

This way I can access it in all of my functions without passing it as
an argument. I am unsure, however, as to wheater it is possible to do
this with seperate source files. For instance can I have:

/* one */
#include <stdio.h>

int num;

int main() {
chnum();
printf("Num is %d\n", num);
return 0;
}

/* two */
#include <stdio.h>

void chnum() {
num = 7;
return;
}

Is this possible? Thanks in advanced.
Nori
 
I

Ian Collins

I know that if I want a variable to be global I can define it as such:

...

int var;

int main() {

...

return 0;
}

This way I can access it in all of my functions without passing it as
an argument. I am unsure, however, as to wheater it is possible to do
this with seperate source files. For instance can I have:
Declare it extern in a common header, or in the other source files where
you wish to use it.
 
K

Keith Thompson

Ian Collins said:
Declare it extern in a common header, or in the other source files where
you wish to use it.

But first, be very sure that a global variable is the best solution to
your problem. It very likely isn't.
 

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,796
Messages
2,569,645
Members
45,371
Latest member
TroyHursey

Latest Threads

Top