B
barcaroller
I have come across the following linker error but I'm unable to explain
it. Assume I have three little source files:
// foo.h
extern int x;
// foo.c
int x = 5;
// bar.c
#include foo.h
int y = x; // <--- linker error here
This compiles fine but the linker complains:
c++ foo.o bar.o -o myexe
Linker error: undefined reference to x'
However, this linker error goes aways when I add one line to foo.c:
// foo.c
#include "foo.h" // <--- new line
int x = 5;
Why would the linker not see 'x' unless I add an 'extern x' to the
source file that defines 'x'?
it. Assume I have three little source files:
// foo.h
extern int x;
// foo.c
int x = 5;
// bar.c
#include foo.h
int y = x; // <--- linker error here
This compiles fine but the linker complains:
c++ foo.o bar.o -o myexe
Linker error: undefined reference to x'
However, this linker error goes aways when I add one line to foo.c:
// foo.c
#include "foo.h" // <--- new line
int x = 5;
Why would the linker not see 'x' unless I add an 'extern x' to the
source file that defines 'x'?