Home > Backend Development > C++ > Why Does My C Code Produce a 'Multiple Definition of `wat'' Error, and How Can I Fix It?

Why Does My C Code Produce a 'Multiple Definition of `wat'' Error, and How Can I Fix It?

Barbara Streisand
Release: 2024-12-04 03:56:10
Original
1027 people have browsed it

Why Does My C   Code Produce a

Multiple Definitions of 'wat' in a C Project

The given code consists of four files: FileA.cpp, FileA.h, FileB.cpp, and FileB.h. When compiled, it encounters an error stating "multiple definition of `wat'".

FileB.h defines an integer variable named 'wat' as follows:

#ifndef FILEB_H_
#define FILEB_H_

int wat;
void world();


#endif /* FILEB_H_ */
Copy after login

Since this header file is included in both FileA.cpp and FileB.cpp, the compiler detects that 'wat' is being defined multiple times. This occurs because the macro FILEB_H_ is not properly defined in all of the header files.

To resolve this issue, the header files should be modified as follows:

FileA.h:

#ifndef FILEA_H_
#define FILEA_H_

#include "FileB.h"
void hello();

#endif /* FILEA_H_ */
Copy after login

FileB.h:

#ifndef FILEB_H_
#define FILEB_H_

extern int wat;  // Declare 'wat' as external
void world();


#endif /* FILEB_H_ */
Copy after login

FileB.cpp:

#include "FileB.h"

int wat = 0;  // Define 'wat' with its initial value
void world()
{
    // More code
}
Copy after login

By using 'extern' in FileB.h, we inform the compiler that 'wat' is defined elsewhere and that it should not search for its definition within the current file. The actual definition of 'wat' is then provided in FileB.cpp, avoiding the multiple definition error.

The above is the detailed content of Why Does My C Code Produce a 'Multiple Definition of `wat'' Error, and How Can I Fix It?. 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