Home > Backend Development > C++ > Why Does Multiple Inclusion of a Header File Cause 'Multiple Definition' Errors in C ?

Why Does Multiple Inclusion of a Header File Cause 'Multiple Definition' Errors in C ?

Barbara Streisand
Release: 2024-12-27 17:00:11
Original
850 people have browsed it

Why Does Multiple Inclusion of a Header File Cause

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;
}
Copy after login
// FileA.h
#ifndef FILEA_H_
#define FILEA_H_
void hello();
#endif
Copy after login
// FileB.cpp
#include "FileB.h"
Copy after login
// FileB.h
#ifndef FILEB_H_
#define FILEB_H_

int wat;
void world();
#endif
Copy after login

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;
Copy after login
// FileB.cpp
int wat = 0;
Copy after login

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!

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