2

I am learning C++ through a Bjarne Stroustrup's "Programming Principles and Practice Using C++" and the first part of the drill of the chapter is to show the use of .h files. The drill is extremely simple and I followed it to the letter but I keep getting 'undefined reference to foo' when I try to compile. I will write the three files down bellow, they are super short.

by the way, std_lib_facilities.h is a .h file the author included that has a few includes in it like iostream as well as 'using namespace std;' and some functions the authors wrote that you need to use from time to time

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

#ifndef MY_H
#define MY_H

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

#endif

my.cpp - includes my.h, defines print_foo() to print value of foo using cout and print(int i) to print the value of i using cout

#include "my.h"
#include "std_lib_facilities.h"

void print_foo()
{
    cout << foo << '\n';
}

void print(int i)
{
    cout << i << '\n';
}

use.cpp - includes my.h defines main() to set the value of foo to 7 and print it using print_foo() and print the value of 99 using print()

#include "my.h"

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

The OS I am using for this is Linux if that helps

user207421
  • 305,947
  • 44
  • 307
  • 483
Jesus
  • 63
  • 3
  • 1
    What part of "undefined reference to foo" you are not sure about? The error message could not be more clear, and you most certainly haven't defined `foo` anywhere. – Sam Varshavchik Sep 07 '17 at 01:15
  • "std_lib_facilities.h" is presumably a file that contains a whole lot of includes and a `using namespace std;` Stop using it as soon as possible. Bringing in includes you don't need just slows your compiler down. And `using namespace std;` can lead to surprises, and is an especially bad idea in a header file since there's no way to reverse it. – aschepler Sep 07 '17 at 01:39

1 Answers1

2

In

extern int foo;

extern means that somewhere out there is an int named foo. But it's not defined here. This is just a declaration of foo's existence, a promise to the compiler that foo will exist when it's needed. The compiler will carry on and allow the use of foo even if it doesn't know where foo is yet.

This means that in one of the cpp files there must be a

int foo;

to define foo and keep this promise.

Documentation on on extern

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • Thanks! Yeah I feel like this a a pretty dumb question I just wasn't sure what was up because the drill practically told you exactly what to do. – Jesus Sep 07 '17 at 03:28