Multiple Definitions of a Variable in C
In C , defining a variable multiple times can lead to compilation errors. This issue can arise when multiple files include a header file, resulting in multiple definitions of the same variable.
Consider the following scenario:
// FileA.cpp #include "FileA.h" int main() { hello(); return 0; }
// FileA.h #ifndef FILEA_H_ #define FILEA_H_ void hello(); #endif
// FileB.cpp #include "FileB.h"
// FileB.h #ifndef FILEB_H_ #define FILEB_H_ int wat; void world(); #endif
When compiling this code, you may encounter the error "multiple definition of wat'" because both FileA.h and FileB.h define the variable wat`.
Solution:
To resolve this issue, we can use the extern keyword. This keyword declares a variable as existing elsewhere in the program and prevents it from being defined multiple times.
// FileB.h extern int wat;
// FileB.cpp int wat = 0;
By declaring wat as extern in FileB.h, we are essentially telling the compiler that the definition of wat exists in another file (FileB.cpp in this case). This ensures that there won't be multiple definitions of the variable and allows the compilation to proceed without errors.
The above is the detailed content of Why Does Multiple Inclusion of a Header File Cause 'Multiple Definition' Errors in C ?. For more information, please follow other related articles on the PHP Chinese website!