chrise
chrise

Reputation: 4253

c++ including .cpp: avoiding multiple definition errors

I have a project that included a couple of files that are included in others

A.h --> B.h means A.h is included in B.h

There are a lot of inclusions like

A.h --> X.h
B.h --> A.h
B.h --> X.h

Which all works fine. Now I have the problem that I need to include a cpp file ( not my file, cant change anything with it ). EDIT: There is no corresponding .h file for this .cpp As soon as I do something like

Z.cpp --> B.h

I get a compiler error for multiple declarations. I also tried

Z.cpp --> B.cpp

Similar result, just less errors ( B.h is included in many other .h files )

How can I include this .cpp?

EDIT: I do understand where the error is coming from, I just wonder if there is some workaround.

Upvotes: 0

Views: 80

Answers (3)

chrise
chrise

Reputation: 4253

Given the comments here, I added my own header file. that solved the problem. thanks for pointing this out.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

If you use QtCreator, then it should build the object files for each source file included in the project.

That's why you get multiple definition errors. You have, say, a source file Z.cpp which gets built into Z.o. Then you have Z.cpp included in B.cpp which gets built into B.o. Now when the linker tries to link Z.o and B.o into the executable program, the symbols defined in Z.cpp will exist in both object files, leading to the errors.

The IDE (QtCreator) will make sure both source files are built and linked together, forming a single executable file. Don't #include any source file into another source file (or worse, header file).

The classes, structures, function prototypes and external variable declarations are (or should be) in the header file that you include. The implementation of the non-inline class or structure member functions and functions are in the source file, the compiler and linker will know how to reference them from the object files.

Upvotes: 2

roalz
roalz

Reputation: 2778

This is basic stuff for C++ software development, I suggest you to read a book for an introduction on how to compile and build a program.

Basically, in C++, you #include *.h files in *.cpp source files,
then you compile each *.cpp file,
then link all the compiled files (usually *.o on *nix or *.obj on Windows) into an executable program, or a library to be then linked in a program.

I would consider really bad practice to #include a *,cpp file into another cpp file.

As you are using QTCreator, you should have a project that already takes care of this process.

Upvotes: 1

Related Questions