Trouble Understanding Linked Files

Jul 2, 2012 at 7:20pm
I fear that I do not properly understand linking. When I use the following code I am unable to compile.
 
source.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
#include<math>
#include<math.h>

#include"class.cpp"

using namespace std;

int main() {
	cout << "Hello World" << endl;
	Shape rectangle;
	rectangle.set_values(3,5);
	rectangle.print_area();
}


 
class.cpp


1
2
3
4
5
6
7
8
9
10
#include"class.h"

void Shape::set_values(int a, int b){
	length=a;
	width=b;
}

void Shape::print_area(){
	cout << "The area is " << length*width << endl;
}


 
class.h


1
2
3
4
5
6
class Shape {
		int length, width;
	public:
		void set_values(int,int);
		void print_area();
};


I get the following compiler errors.

1
2
3
4
In file included from source.cpp:5:
class.cpp: In member function ‘void Shape::print_area()’:
class.cpp:9: error: ‘cout’ was not declared in this scope
class.cpp:9: error: ‘endl’ was not declared in this scope


I thought that if I included iostream in source.cpp I could use its member functions in any further linked file. If I include iostream in class.cpp I get the same compiler errors. I've done some reading on linking but haven't found an explanation that makes clear sense to me.
Jul 2, 2012 at 7:27pm
You should be including "class.h", not "class.cpp" in your source.cpp file.

But the errors stem from the code in class.cpp.

1
2
3
cout << "The area is " << length*width << endl;  // Which namespace?
// Should be...
std::cout << "The area is " << length*width << std::endl;
Last edited on Jul 2, 2012 at 7:27pm
Jul 2, 2012 at 7:44pm
This change did not seem to fix my problem. I now get more than just the 2 original errors.

Your comments did lead me to a solution though.

I was including the files in the correct order. However, I neglected to put using namespace std; at the start of each file.
Topic archived. No new replies allowed.