Is it a good practice to define C++ functions inside header files? [duplicate]

If you want to use a function in multiple source files (or rather, translation units), then you place a function declaration (i.e. a function prototype) in the header file, and the definition in one source file.

Then when you build, you first compile the source files to object files, and then you link the object files into the final executable.

Example code:

  • Header file

      int add(int a, int b);  // Function prototype, its declaration
  • First source file

      #include "functions.h"
      // Function definition
      int add(int a, int b)
          return a + b;
  • Second source file

      #include <iostream>
      #include "functions.h"
      int main()
          std::cout << "add(1, 2) = " << add(1, 2) << '\n';

How you build it depends very much on your environment. If you are using an IDE (like Visual Studio, Eclipse, Xcode etc.) then you put all files into the project in the correct places.

If you are building from the command line in, for example, Linux or OSX, then you do:

$ g++ -c file1.cpp
$ g++ -c file2.cpp
$ g++ file1.o file2.o -o my_program

The flag -c tells the compiler to generate an object file, and name it the same as the source file but with a .o suffix. The last command links the two object files together to form the final executable, and names it my_program (that’s what the -o option does, tells the name of the output file).

Leave a Comment