0

I am currently googling this, but I don't know how to word it. I suspect someone will point me to a duplicate question. But... if I have a file like so

parent.h:

...
include "child.h";
int foo;
...

and the following source file, which is called above via its header file:

child.c:

int display ()
{
    printf ( "%d\n", foo );
}

Now this is a simplified example, currently I am using C++ and I am creating an object, and that object calls a method of another object, like foo declared in the parent file. Naturally I get the following error:

error: ‘foo’ was not declared in this scope

Is there any way to get around this scope issue, or must I pass foo down as a parameter?

puk
  • 16,318
  • 29
  • 119
  • 199

2 Answers2

3

I believe you are looking for extern.

EDIT:

Adding some initial linkage.

Community
  • 1
  • 1
codnodder
  • 1,674
  • 9
  • 10
1

Usually, variables live in the source files...

parent.c

int foo = 0;

...and are externed in the header files...

parent.h

extern int foo;

In this way, whomever #includes parent.h will extern foo.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
  • I think you made a mistake. Shouldn't `parent.c` be `parent.h` (without initialization) and `parent.h` should be `child.h`, correct? – puk Dec 08 '13 at 20:21
  • @Puk14 No mistake. :-D But, there's many ways to accomplish the same goal. – Fiddling Bits Dec 08 '13 at 20:38