简体   繁体   中英

Why does Visual Studio error when linking having files included?

I don't really understand the why behind this, but I think I've figured out the what.

My brother is working on a homework project and they're using Visual Studio. He was having issues getting his project to compile. The project in question consisted of:

main.cpp
classes.h
class_functions.cpp
general_functions.cpp

They had the following import structure:

main.cpp

#include "classes.h"
#include "class_functions.cpp"
#include "general_functions.cpp"

class_functions.cpp

#include "classes.h"

general_functions.cpp

#include "classes.h"

He kept getting link errors when trying to compile, even though g++ would compile it just fine. So I tried via Visual Studio command prompt and cl . This compiled just fine, so I tried msbuild which (obviously?) failed. I went into the vxproj file, because hey, what is it telling cl that I'm not?

In the proj file it was including classes.h , general_functions.cpp and class_functions.cpp , as well as main.cpp . When I removed general and class functions, msbuild ran just fine. Put either of them back and boom . classes.h contains

#ifndef myclasses
#define myclasses
/* Code here */
#endif

And the other .cpp files contain similar directives.

I finally figured out how to eliminate the problem - eliminate

#include "general_functions.cpp"
#include "class_functions.cpp"

from the code base, and now Visual Studio compiles this just fine.

The question is why ? What is the justification or possible benefits from doing this?

the difference between .cpp and .h files is that the .h files are usually included with the #include directive while .cpp files are included in the linking process.

The #include instruction will insert a copy of the included file in the code you are compiling, so by including the .cpp files you will compile a single source file that contains all your .cpp files. It's very bad practice but still could work.

But if you are then adding the .cpp files also in the linking step then you are adding those files a second time creating probably duplicate definitions of your functions, eg linker error. I think that's probably the main error (without the linker error codes I'm just guessing).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM