FAQ: Header files, include statements [Archive] - C Board

PDA

View Full Version : FAQ: Header files, include statements


bennyandthejets
12-28-2002, 08:49 AM
i dont completely understand how compilers process different header files, and also .cpp files.

im trying to formulate a system whereby i can add a class to my program that consists of a .h file and a .cpp file. These files contain completely independent code from the main program that can be added into any program, not based on or derived from any other classes or code. but i cant figure out how to include everything properly. the compiler always tells me this function is already defined or that function isn't defined yet; i have to fiddle around with the include statements a lot to make it work, and it never makes sense.

what is the most efficient way to do this?

for example, say main.cpp and main.h contain code that displays a window, adds child windows, etc. Then i have a class, benClass, that is contained within bClass.cpp and bClass.h. where do i add the includes so that everything functions properly?

and also, changing things around a little, if i have a function in main.h that i want to call from bClass.cpp, where do i include everything? thanks for any advice.

Stoned_Coder
12-28-2002, 09:04 AM
this is how you should split a class over .h and .cpp files and then be able to use in another cpp file...


Point.h

#include<iosfwd>

class Point
{
public:
Point();
Point(int,int);
~Point();
int GetX()const;
int GetY()const;
void SetXY(int,int);
friend std::ostream& operator << (std::ostream&,const Point&);

private:
int X;
int Y;
};


Point.cpp

#include "Point.h"
#include<iostream>

Point::Point() : X(0),Y(0) {}
Point::Point(int x,int y) : X(x),Y(y) {}
Point::~Point() {}
int Point::GetX()const { return X;}
int Point::GetY()const {return Y;}
void Point::SetXY(int x,int y) { X=x; Y=y;}
std::ostream& operator << (std::ostream& os,const Point& p)
{
os<<"( "<<p.X<<","<<p.Y<<" )";
return os;
}


Main.cpp

#include "Point.h"
#include <iostream>

int main()
{
Point p(10,10);
std::cout <<p<<std::endl;
p.SetXY(20,20);
std::cout<<p<<std::endl;
return 0;
}

Not windows specific but will give you the idea.

bennyandthejets
12-28-2002, 09:10 AM
suddenly it works. though i suspect things may get more complicated as my code advances, so expect more posts! thanks a lot.