I have 4 classes:
Server.cpp Logger.cpp Util.cpp Crypto.cpp
The class Server use the object Util.
The program works fine, but now I need to use the object Util also in the class Logger.
But when I put in the code #include “Util.cpp” g++ give me an error because I cannot call again the object.
Eclipse told me about the “redefinition” and “previous declaration” of class Util.
How can I solve this?
You should not include the source cpp files in to another cpp file.
This basically violates the One Definition Rule resulting in redefinition errors.
Include the header file which has the definiition of
Utilclass in whichever class you want to create its objects.Basically, Your code should be organized in this fashion(exception: Templatized code):
Util.h ———–> Contains Definition of class
Utilacts as InterfaceUtil.cpp ———–> Contains Implementation of class
Utilacts as ImplementationHere on whenever you want to create an object of class
Utilin any of the cpp files you includeUtil.hin that cpp file so the compiler knows the definition of classUtil.For ex:
Server.cppwants to create an object ofUtilthen yourServer.cppshould includeUtil.has:Also, don’t forget to add Include guards to your header files.
If the usage of
Utilby another source/header file is limited to creating a pointer toUtilthen you do not need to include the header file, You only need to Forward declare theUtilclass.