且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候需要#include .cpp文件?

更新时间:2022-06-22 22:29:38

使用#include somefilename意味着将 somefilename 的内容替换为include.
通过将#include "LineType.cpp"放入Driver.cpp文件中,可以将每个文件有效地放入一个文件中,然后使用g++ Driver.cpp进行编译就可以了.
当您的讲师使用IDE进行编译时,它将进行单独的编译和链接.因此,它编译了Driver.cpp和LineType.cpp这两个文件都包含LineType.cpp中的定义(由于包含).因此,在进行链接时,她两次在LineType.cpp中定义了所有内容,链接程序不知道该怎么做. 您可以使用

Using #include somefilename means that content of somefilename is put in place of the include.
By putting #include "LineType.cpp" in your Driver.cpp file you efectively put everythig in one file and then compiling using g++ Driver.cpp works fine for you.
When your instructor used IDE for compiling it went on separate compile and linking. So it compiled Driver.cpp and LineType.cpp Both files contain definitions from LineType.cpp due to that include. So when it came to linking, she had everything definded in LineType.cpp twice and linker didn't know what to do. You can compile and link multiple files at once by using

g++ Driver.cpp LineType.cpp 

或使用单独的编译和链接命令

Or using separate compile and linking commands

g++ -c Driver.cpp
g++ -c LineType.cpp

这将生成文件Driver.oLineType.o.然后,您可以通过运行将它们组合在一起

Which will generate files Driver.o and LineType.o. Then you can combine them together by running

g++ Driver.o LineType.o