C/C++ header and implementation files: How do they work?

前端 未结 7 2064
执笔经年
执笔经年 2020-11-30 22:43

This is probably a stupid question, but I\'ve searched for quite a while now here and on the web and couldn\'t come up with a clear answer (did my due diligence goo

7条回答
  •  醉话见心
    2020-11-30 23:46

    When you compile a program, the preprocessor adds source code of each header file to the file that included it. The compiler compiles EVERY .cpp file. The result is a number of .obj files.
    After that comes the linker. Linker takes all .obj files, starting from you main file, Whenever it finds a reference that has no definition (e.g. a variable, function or class) it tries to locate the respective definition in other .obj files created at compile stage or supplied to linker at the beginning of linking stage.
    Now to answer your question: each .cpp file is compile into a .obj file containing instructions in machine code. When you include a .hpp file and use some function that's defined in another .cpp file, at linking stage the linker looks for that function definition in the respective .obj file. That's how it finds it.

提交回复
热议问题