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.
// 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.
To resolve such errors, you can use the following approaches:
extern
in the header file but define them in a single source file.
// 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
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?