Chapter 8 Drill 1 : undefined reference to foo

58 views
Skip to first unread message

JS

unread,
Dec 11, 2017, 7:05:53 AM12/11/17
to PPP-public
I've met a problem when trying to compile chapter 8 drill 1. I did everything that the book tells me but I can't figure what's wrong

//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;
}
void print(int i){
    cout
<< i;
}

//use.cpp
#include "my.h"

int main(){
    foo
= 7;
    print_foo
();
   
print(99);
   
}



the error i got
use.cpp:4: undefined reference to `foo'
my.cpp:6: undefined reference to `foo'

All files are in the same directory.

Can anyone help please?



Christiano

unread,
Dec 12, 2017, 7:31:47 PM12/12/17
to PPP-public
You should try this:

//my.h
extern int foo;
void print_foo();
void print(int);

//my.cpp
#include "my.h"
#include "../std_lib_facilities.h"


int foo;

void print_foo(){
    cout
<< foo;
}
void print(int i){
    cout
<< i;
}

//use.cpp
#include "my.h"

int main(){
    foo
= 7;
    print_foo
();
   
print(99);
   
}

Because "extern int foo" works as a declaration, and "int foo" works as a definition.

Does it solve the problem?

JS

unread,
Dec 13, 2017, 1:56:14 AM12/13/17
to PPP-public
That worked, thanks.
Reply all
Reply to author
Forward
0 new messages