C++ Header and CPP includes

流过昼夜 提交于 2019-12-01 21:49:20

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.

No.

Your program is built in phases.

  • 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`
    
  • 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`
    

    (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.)

The two phases can be done at the same time, with the "shorthand":

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

No, the .cpp file does NOT automatically get compiled. You can either do that manually, create a makefile, or use an IDE that has both of them in the same project.

You don't specify how you are compiling it. If you are using an IDE and have a new .h and .cpp to the project automatically then it will all be compiled and linked automatically.

There are 2 stages to making an executable to run: compiling and linking. Compiling is where the code gets interpretted and translated into lower level code. Linking is where all of the functions that you used get resolved. This is where you got the duplicate function error.

unwind

Inclusion does not automatically cause compilation, no.

In fact, the actual compiler never sees the #include statement at all. It's removed by an earlier step (called the preprocessor).

I'm not sure how it could build if you never compiled the Dog.cpp file. Did you reference any objects with code defined in that file?

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!