Home > Backend Development > C++ > Why Am I Getting a 'Multiple Definitions for 'wat'' Compile-Time Error in C ?

Why Am I Getting a 'Multiple Definitions for 'wat'' Compile-Time Error in C ?

Susan Sarandon
Release: 2024-12-08 07:04:16
Original
839 people have browsed it

Why Am I Getting a

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_ */
Copy after login

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:

  1. Declare wat as an extern variable in FileB.h:
extern int wat;
Copy after login

This informs the compiler that wat will be defined elsewhere.

  1. Define wat in FileB.cpp:
int wat = 0;
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template