Hello people,
I am a complete newbie to programming, and I am having some trouble completing a very simple drill in Stroustrups Book Programming Principles and Practice using C++.
I have 3 very simple program parts, my.h , my.cpp, and use.cpp. This is how each of them looks:
my.h
1 2 3
|
extern int foo;
void print_foo();
void print(int);
|
my.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
#include <string>
#include "my.h"
using namespace std;
void print_foo()
{
cout <<"\n"<<foo<<"\n";
}
void print(int i)
{
cout <<"\n"<<i<<"\n";
}
|
and use.cpp
1 2 3 4 5 6 7 8 9
|
#include "my.h"
int main()
{
int foo = 7;
print_foo();
print(99);
return 0;
}
|
Now, when I try to compile using g++ use.cpp, I first get two problems. Firstly, I get a message saying undefined reference to foo in function print_foo(). I'm not really sure how I should be doing this instead. In the book it says I should use main in use.cpp to set the value of foo to 7. Does defining foo within main not set its value for foo everywhere?
Also, I am having problems with undefined reference to print_foo() and print(int). According to the book, my.h should contain exactly what is given above, so is this a problem with the way I am compiling? (am running Ubuntu, using g++ compiler)
Even when I stuff all the code into one file, like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <iostream>
#include <string>
using namespace std;
void print_foo();
void print(int);
extern int foo;
void print(int i)
{
cout << "\n" << i << "\n";
}
int main()
{
int foo = 10;
print_foo();
print(99);
return 0;
}
void print_foo()
{
cout << "\n" << foo << "\n";
}
|
I get the undefined reference to foo error. I am really confused here, and would greatly appreceate any help in showing / explaining to me what I am doing wrong here.
Thank you in advance!!!