How exactly does a header file or any forward declarations know which definition it is referring to?
I understand that .cpp files are compiled independently, and we need a header file or forward declaration to access members of another .cpp file. But when we declare a member, we don't explicitly tell the compiler where to get the definition from.
Here is a case that I can think of: Say I have two cpp files 'one.cpp' and 'two.cpp'. Both 'one.cpp' and 'two.cpp' have a member 'int func(int x)' that have different implementations (but have the exact name and format). If we have a header file or declaration of this function somewhere outside these two files, how does the compiler know which definition to take?
Resolving a definition for each declaration is performed by the linker. Each declaration must have a unique definition. While a function may be declared multiple times, each function must be defined exactly once in all compilation units which are to be linked. If there is more than one definition for a function with the same signature, then the linker will throw an error and refuse to finish building the executable.
I suggest that you create the example files that you described and try to build them into a single executable. You will see the error that I describe here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With