0

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.

  • 1
    You need to post your code so we can see what you're doing wrong. – Barmar Sep 30 '15 at 22:38
  • 1
    It would be great if you could enclose a [mcve]? – t0mm13b Sep 30 '15 at 22:39
  • I have read that - and other sources. Some sources suggest I could achieve this using header files and that's what I'm trying to do. –  Sep 30 '15 at 22:45
  • @Barmar I have done so now. –  Sep 30 '15 at 22:45
  • Important question - how are you compiling/linking it? Makefile? – t0mm13b Sep 30 '15 at 22:46
  • @t0mm13b Yes. I will also edit my makefile into the OP. –  Sep 30 '15 at 22:47
  • ` main: a.o b.o gcc $(CFLAGS) -o main $^ ` – Petr Skocik Sep 30 '15 at 22:51
  • `gcc -E` should give you a clue on how the C compiler pre-processes the output. What version is the compiler? I have tried it here with gcc 4.9 and do not get the error. – t0mm13b Sep 30 '15 at 22:56
  • @t0mm13b Strange! Also 4.9. It says (in my b.c class) that i has not been declared when I do i = 10;. –  Sep 30 '15 at 23:42
  • @t0mm13b I am ever so confused. Make a new directory, copied and pasted all the files, ran the makefile and it compiled in the new directory with 0 errors. Still doesn't run in the old directory. What the hell is up with that...? –  Oct 01 '15 at 00:02

1 Answers1

0

Go ahead and include the header with the ext in both files. Put the definition and initialization in the file that owns the variable. This is okay:

extern int aaa;
int aaa = 1;
Barmar
  • 741,623
  • 53
  • 500
  • 612
Steve Kolokowsky
  • 423
  • 2
  • 12