How do I fix multiple definition errors in C++?

In C++, multiple definition errors occur when the same function or variable is defined in more than one translation unit. This typically happens when header files are included in multiple source files without proper include guards or when variables are defined in a header file instead of declared as extern.

Example of a Multiple Definition Error

// File: my_functions.h int myFunction() { return 42; } // File: main.cpp #include "my_functions.h" int main() { return myFunction(); } // File: another_file.cpp #include "my_functions.h" void someFunction() { myFunction(); }

In the example above, the function myFunction is defined in the header file my_functions.h and included in two different source files. This will lead to a multiple definition error during linking.

Fixing Multiple Definition Errors

To resolve such errors, you can use the following approaches:

  • Declare functions in header files and define them in one source file.
  • Use include guards in header files to prevent multiple inclusions.
  • For global variables, declare them extern in the header file but define them in a single source file.

Example Fix with Include Guards

// File: my_functions.h #ifndef MY_FUNCTIONS_H #define MY_FUNCTIONS_H int myFunction(); // Declaration #endif // MY_FUNCTIONS_H // File: my_functions.cpp #include "my_functions.h" int myFunction() { return 42; // Definition }

multiple definition errors C++ include guards fixing errors function declaration extern keyword