I am a beginner in c++ and I've a problem with header file management. I have a class, Matrix, with it's on .h and .cpp files. I've a second class, Map, with it's own .h and .cpp files too. Map.h includes Matrix.h, and so far it works. But when I go to code the implementation of Map (in Map.cpp) and I use stuff defined in Matrix.h, it gives me a undefined reference error. including Matrix.cpp does resolve the problem, but I know that that's a bad practice. So, what am I supposed to do and why?
Thank you very much!
EDIT: i did a test. i threw in Matrix.h a function declration, Implemented it in Matrix.cpp and then used it in Map.cpp. it did work without including Matrix.cpp. It's onl开发者_开发问答y with things belonging to the Matrix class that things go crazy.
Probably your problem is that you forgot to compile Matrix.cpp. This seems to be a surprisingly (to me) common mistake. How are you invoking your compiler?
First I'll ask the obvious; have you #include
ed Map.h
in Map.cpp
?
I would also point out that Map.h
may not need to include Matrix.h
at all. If your only references to a Matrix
in Map.h
are pointer/reference arguments then you can simply forward declare the class:
// forward declare some currently unknown type "Matrix"
class Matrix;
class Map
{
public:
void SomeOperation( const Matrix& matrix );
};
As long as the argument is a pointer or reference type then the compiler does not need to know the size of a Matrix
and thus everything just works. This is better than including more headers in your .h files if you can do it. Then you will include both Matrix.h
and Map.h
in your Map.cpp
file.
You might want to include both .h files in the compilation, in order of need to have definitions work out, instead of through each other.
Then you should link to Matrix.o, based on the assumption that you are defining a symbol in Matrix.cpp that is needed to compile Map.cpp. Is this what is happening?
Simple rules:-
- Use guards in header files like:-
ifndef MATRIX_H
define MATRIX_H
... ... header file things ...
endif
Have all class definitions/other declarations in header file. Definitions in related .cpp files.
Always try to avoid including one header file from another header file as far as possible. An extern declaration will do most of the times. Linked will automatically resolve the reference.
It is ok to include a header file from .cpp file. But here also, most of the times things do only with an extern declaration.
精彩评论