C ++头和CPP包括 [英] C++ Header and CPP includes

查看:208
本文介绍了C ++头和CPP包括的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

快速问题。

我试图让C ++钉死,今天我花了几个小时与一个双定义链接器错误(这已经定义! )我终于意识到这是因为我有这样的布局:

I am trying to get C++ nailed down, and today I spent hours with a double definition linker error("this has already been defined!") and I finally realised it's because I had the layout as such:


  • main.cpp

  • main.cpp

#include Dog.cpp


  • Dog.cpp

  • Dog.cpp

    #include Dog.h
    


  • Dog.h

  • Dog.h

    // (Dog class and prototype of test function)
    


  • 通过在main.cpp中包含Dog.h而不是Dog.cpp来清除它。

    And now that I've cleared that up by including the Dog.h instead of the Dog.cpp in the main.cpp.

    通过包含.h文件, .cpp文件与相同的前缀编译程序?

    我惊讶的是,程序运行时只包含.h包括没有参考Dog.cpp。我花了很多年的时间在Google上,但没有答案真的帮助我了解发生了什么。

    I was astounded when the program ran with only the .h included and no references whatsoever to Dog.cpp. I spent ages Googling but no answers really helped me understand what was going on.

    编辑:我忘了添加我原型。 h,并为.cpp中的类定义了函数,这就是给定的已定义错误。

    Edit: I forgot to add that I prototyped in the .h, and defined the function for the class in the .cpp and that's what gave me the "already defined" error.

    推荐答案


    通过包含.h文件,具有相同前缀的.cpp文件是否与程序一起编译?我很惊讶,当程序运行时只有.h包含,没有参考任何Dog.cpp。

    By including the .h file, does the .cpp file with the identical prefix get compiled with the program? I was astounded when the program ran with only the .h included and no references whatsoever to Dog.cpp.

    否。

    您的程序分阶段开发。


    • 阶段,每个翻译单元中只需要声明(大致相当于解析了 #include 的单个.cpp文件)。

    • For the compilation phase, only declarations are needed in each translation unit (roughly equivalent to a single .cpp file with #includes resolved). The reason that declarations even exist in the first place is as a kind of "promise" that the full function definition will be found later.

    g++ -c Dog.cpp               # produces `Dog.o`
    g++ -c main.cpp              # produces `main.o`
    


  • 对于链接阶段,符号在翻译单位之间进行解析。你必须将编译Dog.cpp和编译main.cpp的结果连接在一起(也许你的IDE是为你做的),这个链接进程在它们之间找到所有正确的函数定义,产生最终的可执行文件。 p>

  • For the linking phase, symbols are resolved between translation units. You must be linking together the result of compiling Dog.cpp and of compiling main.cpp (perhaps your IDE is doing this for you?), and this link process finds all the correct function definitions between them to produce the final executable.

    g++ Dog.o main.o -o program  # produces executable `program`
    

    (或者,你实际上还没有进入链接阶段,只有一个目标文件(Dog.o);你不能执行它,部分是因为它没有所有的函数定义。)

    (Either that, or you actually haven't got to the link phase yet, and merely have an object file (Dog.o); you can't execute it, partially because it doesn't have all the function definitions in.)

    同时,用简写:

    g++ Dog.cpp main.cpp -o program  # compiles, links and produces executable
    

    这篇关于C ++头和CPP包括的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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