Chapter8_Drill

38 views
Skip to first unread message

yuanwxu

unread,
May 20, 2012, 6:52:48 AM5/20/12
to PPP-public
Hi, this might be as simple as "hello world" but I can't compile it
successfully. I have :
my.h:

extern int foo;
void print_foo();
void print(int);

my.cpp:

#include "my.h"
#include "std_lib_facilities.h"
void print_foo()
{
cout<<foo<<endl;
}
void print(int i)
{
cout<<i<<endl;
}

and use.cpp:

#include "my.h"
int main()
{
foo=7;
print_foo();
print(99);
}

The error is : In function "main": undefined reference to 'foo', but I
have already declared this variable in my.h

Jeffrey Diaz

unread,
May 20, 2012, 2:18:26 PM5/20/12
to ppp-p...@googlegroups.com
Your statement extern int foo; tells the compiler you want access to a
global variable named foo who was declared in another c++ module
(source file NOT header file), so you do not need the extern qualifier
here at all since foo is not declared in another module. However, if
you remove the qualifier you will get a linker error (try it!) since
you will now have two global variables named foo (since you included
"my.h" in both modules, both will place int foo in the global space
causing a collision).

Here is when you would need the "extern" qualifier:

my.h

void print_foo();
void print(int);

my.cpp
#include "my.h"
int foo = 0; // Global space. In a C++ module.
void print foo() { }
void print(int i) { }

use.cpp
#include "my.h"
extern int foo; //Bring the global variable defined in my.cpp into scope.
int main() { }
> --
> You received this message because you are subscribed to the Google Groups "PPP-public" group.
> To post to this group, send email to ppp-p...@googlegroups.com.
> To unsubscribe from this group, send email to ppp-public+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/ppp-public?hl=en.
>
Reply all
Reply to author
Forward
0 new messages