Home >Backend Development >C++ >How to Resolve 'Multiple Definition of Variable' Errors in C ?
Multiple Definition of Variable in C
When working with multiple files in C projects, you can encounter errors related to multiple definitions of a variable. Consider the following situation:
FileA.cpp:
#include "FileA.h" int main() { hello(); return 0; } void hello() { //code here }
FileA.h:
#ifndef FILEA_H_ #define FILEA_H_ #include "FileB.h" void hello(); #endif /* FILEA_H_ */
FileB.cpp:
#include "FileB.h" void world() { //more code; }
FileB.h:
#ifndef FILEB_H_ #define FILEB_H_ int wat; void world(); #endif /* FILEB_H_ */
Upon attempting to compile this code, you might encounter an error stating "multiple definition of `wat'."
Explanation:
The error arises because you have defined a global variable, wat, twice in your compilation unit. Both FileA.h and FileB.h include a declaration of wat, defining it twice in the global scope.
Solution:
To resolve this issue, follow these steps:
FileB.h:
extern int wat;
FileB.cpp:
int wat = 0;
By using extern in FileB.h, you inform the compiler that a variable named wat exists somewhere else. In this case, you define the actual variable with an initializer in FileB.cpp.
This approach ensures that wat is declared once in the global scope, eliminating the multiple definition error.
The above is the detailed content of How to Resolve 'Multiple Definition of Variable' Errors in C ?. For more information, please follow other related articles on the PHP Chinese website!