Hi , sorry for newbie quiestion, but i have some difficulty writing c++ app with many files. I declared some class in `frame.hpp` and defined it in `frame.cpp`
First time I included `frame.hpp` in main.cpp and the compiler gives me an error that it can't find class's definition (which is logical) , so I included `frame.cpp` in main file and everything works fine . Am I doing it wrong ? What I must do ?
.....frame.hpp
class frame (){};
.....
.....frame.cpp
#include "frame.hpp"
// definition ...
.....
.....main.cpp
#include "frame.hpp"
.....
In this way I got error but when I did it this way everything works fine
.....frame.hpp
class frame (){};
.....
.....frame.cpp
#include "frame.hpp"
// definition ...
.....
.....main.cpp
#include "frame.cpp"
.....
P.S. sorry for my bad english , it's not my native language :)
I thought that header files should have a .h naming convention. Why have you used .hpp?
Ive written an example classes program that uses multiple files that compiles and runs just fine. You only need to include the header file in both .cpp files; see below:
1 2 3 4 5 6 7 8 9 10 11
// addNumbers.h
// addNumbers class definition
class CaddNumbers
{
int a;
int b;
public:
CaddNumbers(int x, int y) { a = x; b = y; }
int add();
};
1 2 3 4 5 6 7 8
// addNumbers.cpp
#include "addNumbers.h"
int CaddNumbers::add(void)
{
return (a+b);
}
Thanks for replies guys !
@demonwolf .hpp extension is c++ header file while .h is for c
But how compiler will know where is the definition of `CaddNumbers` class ???
It only knows that the declaration is in addNumbers.h . Is it searching for available definitons ???
The addNumbers.cpp file is in the sources folder of the environment I use (VS 2008) and adds it into the main program at link time.
The header file is added/included into the main program at compile time producing a main.o object file (if you call the primary file main.cpp). The addNumbers.cpp file is also compiled producing an addNumbers.o; these two files are then linked to produce a main.exe file.
I learnt multiple files and header files from these sources:
The diagram in the second link is helpful to be able to visualise the whole process of compiling and linking your files.
thanks moorecm for the reminder heres the updated header file with inclusion guards:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#ifndef _ADDNUMBERS_
#define _ADDNUMBERS_
// addNumbers.h
// addNumbers class definition
class CaddNumbers
{
int a;
int b;
public:
CaddNumbers(int x, int y) { a = x; b = y; }
int add();
};
#endif