2

I don't quite understand how the main.cpp knows to use class definitions and function definitions from a header's source file.

I understand how #include HeaderName.h is able to include class declarations, because we tell main.cpp to include it. However, not in the header file nor main.cpp is the program told to get the class and function definitions from the HeaderSource.cpp. So, how does it know that the definitions for the declared classes are in there?

mrflash818
  • 930
  • 13
  • 24
torhara
  • 101
  • 6
  • 2
    It doesn't, generally. That's handled by the linker. How are you linking your code - are you compiling all of the sources in one go e.g. `g++ main.cpp HeaderSource.cpp` ? Try leaving off the `HeaderSource.cpp` and see what happens. – Rup Sep 02 '19 at 02:11
  • thanks for the response ^^ I'm skeptical because there is no include for the source file, just the header, inside of main and the source – torhara Sep 02 '19 at 02:12
  • @Rup thanks that helps! i didn't realize a linker took care of it. I haven't really compiled yet I'm just learning online – torhara Sep 02 '19 at 02:13
  • 1
    Related: [How does the compilation/linking process work?](https://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) – user4581301 Sep 02 '19 at 03:28

1 Answers1

4

Each cpp file is compiled separately; they're each a 'translation unit' that shares no definitions with each other. You can test that by defining something in a cpp file and not defining it in a header; no other cpp file will know about it.

The object files that are produced by compilation are then 'linked' together by a linker; that linker can see each object file so it knows where all the definitions of functions are.

This question has an answer that goes into significant detail about how it works for x86 ELF files. It's important to know that this process is going to be a bit different and will work differently for different systems.

James Picone
  • 1,509
  • 9
  • 18