Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concept: How are declarations linked to apropriate definitions

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?

like image 954
Steven.Cooler Avatar asked Sep 01 '25 22:09

Steven.Cooler


1 Answers

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.

like image 200
Code-Apprentice Avatar answered Sep 03 '25 12:09

Code-Apprentice