Home >Backend Development >C++ >Why Am I Getting a 'Multiple Definitions for 'wat'' Compile-Time Error in C ?
Multiple Definition of Variables in C
Encountering a compile-time error of "multiple definitions for wat" can be perplexing. Let's analyze the provided source code and identify the issue.
In your code, you have four files: FileA.cpp, FileA.h, FileB.cpp, and FileB.h. When compiling, the compiler detects multiple definitions of a variable named wat.
Upon inspection, you have defined the variable wat in both FileA.h and FileB.h:
// FileA.h void hello(); #endif /* FILEA_H_ */ // FileB.h int wat; void world(); #endif /* FILEB_H_ */
When your code is compiled, the header files are included in the compilation unit multiple times, leading to duplicate definitions of the variable wat. To resolve this issue, you need to separate the declaration of wat from its definition.
Solution:
extern int wat;
This informs the compiler that wat will be defined elsewhere.
int wat = 0;
Now, when compiling, the compiler will correctly identify wat as being declared in FileB.h and defined in FileB.cpp, resolving the multiple definition error.
The above is the detailed content of Why Am I Getting a 'Multiple Definitions for 'wat'' Compile-Time Error in C ?. For more information, please follow other related articles on the PHP Chinese website!