Question:
C++ - Interface and Implementation in separate files not working!?
monty
2008-12-30 18:52:38 UTC
I'm VERY new to C++, and am using a tutorial e-book. It's up to the point where I learn about classes. It separates the class into two files, with the interface in the .h file, and the implementation in a .cpp file.

However, when I try to compile the test program it doesn't work! The interface is ITEM1.h, the implementation is ITEM1.cpp, and I've got the #include "ITEM1.h" in the test program. The error is something to do with StockItem::StockItem() (which is the class, with the default constructor) not being defined correctly. If I copy and paste the stuff from the implementation file into the test program, above main(), it works.


Why isn't it realizing where the implementation .cpp file is? Is it my fault? A compiler error? Something I haven't specified? ANY help would be appreciated.


Thanks in advance!
Three answers:
cja
2008-12-31 05:55:23 UTC
I don't know what compiler you're using, but with g++ I'd do this:



> g++ -c ITEM1.cpp

> g++ -o itemTst itemTst.cpp ITEM1.o



The first line compiles ITEM1.cpp and creates the object file ITEM1.o.

The second line compiles the test program, and links in ITEM1.o.



Whatever compiler you're using, you need to do something similar. The fact that you said it works when you copied the contents of ITEM1.cpp into your test program makes me think that when you had ITEM1.cpp separate you weren't linking ITEM1.o with your test program. Without seeing your code or development environment, though, it's hard to say for sure if this is your problem.
cyree
2016-10-19 13:46:15 UTC
some classes are hundreds of lines massive. you haven't any longer seen massive classes; in case you had then you certainly might comprehend why classes are no longer all put in one report. that is like once you force a vehicle. many times the only area of the vehicle you notice is the dashboard. you do no longer ought to renowned how the engine works or maybe see it. So a type customer is almost a driving force of a vehicle, acceptable? i think a type specification may well be like a dashboard and the implementation may well be the engine. That analogy isn't completely precise yet i desire it enables for undertstanding training.
The Phlebob
2008-12-30 19:04:03 UTC
This sounds like the preprocessor (the thing that interprets all the # lines, including the #include lines) might not be finding the header (.h) file. Make sure it's in the correct directory and that the compiler is aware of that directory.



Also, make sure only ONE #include "Item1.h" line is being processed. Defining the class twice will cause problems.



Hope that helps.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...