To set the scene here - I have 2 .c files, call it a.c
and b.c
.
I then have 2 header files for each .c file, a.h
(which has all function prototypes, and all global variables declared as extern type name;
), and b.h
which has only function prototypes of b.c
as b.c
contains no global variables.
I want to access a.c
's global variables in b.c
, so I have added a statement #include "a.h"
in b.c
.
Only problem is, I still can't access a.c
's global variables in b.c
, for example if I want to print. I have a global variable int i;
in a.c
, and if I do:
i = 5;
printf("%d", i);
in b.c
, I get an error saying that variable i has not been declared. What am I doing wrong?
The code:
a.c:
#include "b.h"
int i;
int main() {
executeMethod();
return 0;
}
b.c:
#include "a.h"
void executeMethod() {
i = 10;
printf("%d", i);
a.h:
int main();
extern int i;
b.h:
void executeMethod();
makefile:
CFLAGS=-Wall -g
all: main
main: a.c b.c a.h b.h
gcc $(CFLAGS) -o main a.c b.c a.h b.h
clean:
rm -f main
Have also tried without the makefile: gcc -o main a.c b.c a.h b.h
Thanks.
Edit: it works if I define extern int i;
on top of my b.c
file, but say I have 60 variables, I would rather have them in a header.h file and just #include "header.h"
rather than writing 50 extern statements.