0

Is it needed to put function declarations in header files and their definitions in a source files? Is there any performance gain, or possibly any advantage to doing this instead of putting the declarations and definitions in the same file? Example:

In Person.h

class Person() {
public:
    void sayHi();
}

and in Person.cpp

#include "Person.h"
#include <cstdio>

void Person::sayHi() {
    printf("Hello, world!\n");
}

versus just having it in one file:

#include <cstdio>

class Person {
    void sayHi() {
        printf("Hello, world!\n");
    }
}
  • Not needed. No performance advantage (to the executable) either way. Please review "compilation unit". – 2785528 Jun 04 '20 at 01:01
  • Which file do you envision in your one-file version? Would it be like a header file, read for every source file that uses the function? Like a source file, where no other source files get to see what's in it? – JaMiT Jun 04 '20 at 01:10

1 Answers1

2

If you put the definition in the .cpp file, then you can change the definition without having to recompile all the other .cpp files as well. If it's in the header, then every .cpp file that includes the header will also need to be recompiled to have the new definition.

The runtime performance will be exactly the same. Compilation times may differ but it depends on how the project is compiled (and whether the compilation time difference is noticeable depends on how large your project is).

In general, I tend to place almost all definitions in a .cpp file. In my unscientific opinion, I feel that it encourages reliance on the interface alone (since the "user" of the class can't necessarily see how it's implemented).

dreamlax
  • 93,976
  • 29
  • 161
  • 209