Search code examples
c++functionheader-files

Is it needed to put function declarations in header files and their definitions in a source files?


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");
    }
}

Solution

  • 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).