0

When using multiple files in C++, for example: main.cpp, definition.cpp, declaration.h

// declaration.h
int Myfunc();
//definition.cpp
#include "declaration.h"

int MyFunc() {return 5;};
// main.cpp
#include <iostream>
#include "declaration.h"

int main()
{
    std::cout << Myfunc() << std::endl;
}

Why do I not need to include the definition file into the main file? How can the program know the definition of Myfunc() when I only have included the declaration?

Viktor Skarve
  • 129
  • 1
  • 8
  • How are you compiling the program? Is there a configuration file of any sort, or is this a Visual Studio project? – Mooing Duck Dec 10 '20 at 17:21
  • 2
    The definition is included into the executable in the linking step of the build process. See, e.g. https://stackoverflow.com/q/6264249/9988487 for more details. – Adomas Baliuka Dec 10 '20 at 17:22
  • 3
    It's the responsibility of Linker. – Raindrop7 Dec 10 '20 at 17:22
  • I think the [second answer](https://stackoverflow.com/a/333964/5105949) explains your problem. – Lukas-T Dec 10 '20 at 17:23
  • Because of the next phase: "Linking". Usually what happens: Compilation does `definition.cpp => definition.o` and `main.cpp => main.o` Then we link the object files into an executable: `main.o + definition.o => application` – Martin York Dec 10 '20 at 17:29
  • Including the header makes the names used in source file searched in that header and other headers. The compilers is satisfied with a name declaration like in your case when it compilation terminates there are object files for each translation unit. The linker links those object file (containing definitions) with some other libraries generating the executable file. If the linker doesn't find the definition it fails to link. – Raindrop7 Dec 10 '20 at 17:32
  • I wrote some articles about this problem; you may find them [here](https://yact.tech/en/posts/05_declarations_and_definitions_I.html) and [here](https://yact.tech/en/posts/06_declarations_and_definitions_II.html). – Daniel Langr Dec 10 '20 at 17:35

1 Answers1

0
  • Declaration is like a signature of the function and at compile time only the signature is required (What variable to pass and what the function will return so that you can write your other code around it). Actual call to function is resolved during the link time. If you will include the definition in the header file and if that header file is included in multiple source file then there will be multiple definitions of the same function.
TKA
  • 183
  • 2
  • 4