Not that I want to see GQ filled with programming questions, but this has been bugging me all afternoon and various textbooks and websites offer no assistance. I’m attempting to write a program that draws a clockface, using what I thought were proper .h and .cpp files, which have been boiled down to the following:
Now I thought it was good practice to put the method prototype in the header and the code in the .cpp file, but I’m consistently getting “error LNK2005…drawHours(int) already defined in clockface.obj”.
I’m fully prepared to admit I may be overlooking something obvious.
I don’t think there’s anything wrong with the code as posted; you should be able to include clockface.h in multiple source files with no problem. Perhaps the problem is in the details omitted in the “boiling down” process?
Ah yeah, that’s a definite possibility. It’s the sort of thing you could easily type by mistake, miss on several skims of the source, and would result in the reported linker error.
Well, an include for clockface.cpp is in the file with the main (clocktower.cpp, which I hope to be the overall program and which will call other tower components as I write them) and I can vaguely see how #including clockface.cpp (which #includes clockface.h) could lead to a double-definition, but how else do you write master functions?
If I rem out clocktower’s “#include clockface.cpp” statement, the error goes away, but so does any chance of actually getting a clock face. Both clockface.h and .cpp begin with appropriate #ifndef statements.
You’re not supposed to #include the .cpp file. All #include does is physically dump the text from an external file into the current file before compiling, and you don’t need the definitions of your functions to be dumped into multiple compilation units: that will result in multiple definition errors. All you need is the declaration in the .h; the definition in the clockface.obj will be “linked in” by the linker – that’s exactly what the linker’s job is, so when it finds multiple definitions for the same function signature in multiple object files, it gets confused.
Remove the #ifndef guard from clockface.cpp and just include clockface.h.
Yeah, that’s the whole reason for having separate files – the .h contains just the information needed for the interface, so other objects know how to talk to it, while the .cpp file contains all the code.
At least, that’s the idealization. In fact the .h typically includes way more information than is needed for the interface, namely all the private fields and methods. Semantically, other scopes don’t “know” about these things, but in practice it leads to considerable compile-time dependencies, and that’s why we have things like the PIMPL idiom.