什么时候需要#include .cpp文件? [英] When do I need to #include .cpp files?

查看:131
本文介绍了什么时候需要#include .cpp文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一项家庭作业涉及三个文件:LineType.h,LineType.cpp和Driver.cpp. Driver.cpp包含main()方法,该方法使用LineType.h和LineType.cpp定义的类.

One of my homeworks involves three files: LineType.h, LineType.cpp, and Driver.cpp. Driver.cpp contains the main() method which uses a class defined by LineType.h and LineType.cpp.

在我的系统上,Driver.cpp开头为:

On my system, Driver.cpp starts with:

#include "LineType.h"
#include "LineType.cpp"
#include <iostream>

当我通过命令行从项目目录中运行g++ Driver.cpp时,程序将编译并完美运行.但是,当我的讲师尝试编译程序时(我相信她使用Eclipse),则编译失败.经过反复反复,她能够通过注释掉Driver.cpp中的#includes之一来解决此问题:

And the program compiles and runs perfectly when I run g++ Driver.cpp from within the project directory via the command line. However, when my instructor attempts to compile the program (I believe she uses Eclipse), it fails to compile. After some back-and-forth, she was able to fix the problem on her end by commenting out one of the #includes from Driver.cpp:

#include "LineType.h"
//#include "LineType.cpp"
#include <iostream>

当我尝试在此编辑的文件上运行g++ Driver.cpp时,我的编译器抱怨未定义的体系结构符号",我理解这意味着它无法找到所调用的类/方法的定义.

When I attempt to run g++ Driver.cpp on this edited file, my compiler complains about "Undefined symbols for architecture", which I understand to mean that it cannot find definitions for the class/methods being called.

我的老师和我在做些什么来导致这种行为上的差异?为什么我的编译器所需的一行会导致其编译器失败?

What are my instructor and I doing differently to cause this difference in behavior? Why does a line required by my compiler cause her compiler to fail?

推荐答案

使用#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

这篇关于什么时候需要#include .cpp文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆