Global variables.

P

pereges

Let's say I've a header file foo.h containing a global variable a.

/* foo.h */
#ifndef foo_h
#define foo_h

#include <stdio.h>

extern int a;
#endif

Now, suppose I want to access this variable in main.c, then I need to
include foo.h

/* main.c */

#include "foo.h"
#include <stdio.h>

int a;

int main()
{
a = 4;
return (0);
}

My question is why must I always declare the integer again in main.c
and that outside the function ( I got a warning for not doing so)
whereas the definition must be in the main routine.
 
V

viza

Let's say I've a header file foo.h containing a global variable a.
extern int a;
Now, suppose I want to access this variable in main.c, then I need to
#include "foo.h"
int a;
My question is why must I always declare the integer again in main.c and
that outside the function

extern int a; tells the compiler that a is an int, and that the linker
has to look for it later. int a; actually allocates storage for the
variable. The later must occur in exactly one file, the former should
occur everywhere else that you want to access the variable and may occur
included there as well.
 

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
473,769
Messages
2,569,582
Members
45,062
Latest member
OrderKetozenseACV

Latest Threads

Top