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

Nobody picture Nobody · Aug 12, 2014 · Viewed 88k times · Source

I'm wondering if it's a good practice to store C++ regular functions, not methods(the ones in classes) inside header files.

Example:

#ifndef FUNCTIONS_H_INCLUDED
#define FUNCTIONS_H_INCLUDED

int add(int a, int b)
{
   return a + b;
}

#endif

And Use it like this:

#include <iostream>
#include "Functions.h"

int main(int argc, char* args[])
{
    std::cout << add(5, 8) << std::endl;
    return 1;
}

Is this a good a good practice? Thanks in advance!

Answer

Some programmer dude picture Some programmer dude · Aug 12, 2014

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

      #ifndef FUNCTIONS_H_INCLUDED
      #define FUNCTIONS_H_INCLUDED
    
      int add(int a, int b);  // Function prototype, its declaration
    
      #endif
    
  • 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).