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 googling).
So I'm new to programming... My question is, how does the main function know about function definitions (implementations) in a different file?
ex. Say I have 3 files
//main.cpp #include "myfunction.hpp" int main() { int A = myfunction( 12 ); ... }
-
//myfunction.cpp #include "myfunction.hpp" int myfunction( int x ) { return x * x; }
-
//myfunction.hpp int myfunction( int x );
-
I get how the preprocessor includes the header code, but how do the header and main function even know the function definition exists, much less utilize it?
I apologize if this isn't clear or I'm vastly mistaken about something, new here
A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.
In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”. All the header file have a '. h' an extension.
An implementation file is used in C++ programming when creating a class definition to split the interface from the implementation. The header file would declare all the member functions (methods) and data methods (fields) that the class has.
To minimize the potential for errors, C++ has adopted the convention of using header files to contain declarations. You make the declarations in a header file, then use the #include directive in every . cpp file or other header file that requires that declaration.
The header file declares functions/classes - i.e. tells the compiler when it is compiling a .cpp
file what functions/classes are available.
The .cpp
file defines those functions - i.e. the compiler compiles the code and therefore produces the actual machine code to perform those actions that are declared in the corresponding .hpp
file.
In your example, main.cpp
includes a .hpp
file. The preprocessor replaces the #include
with the contents of the .hpp
file. This file tells the compiler that the function myfunction
is defined elsewhere and it takes one parameter (an int
) and returns an int
.
So when you compile main.cpp
into object file (.o extension) it makes a note in that file that it requires the function myfunction
. When you compile myfunction.cpp
into an object file, the object file has a note in it that it has the definition for myfunction
.
Then when you come to linking the two object files together into an executable, the linker ties the ends up - i.e. main.o
uses myfunction
as defined in myfunction.o
.
I hope that helps
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