Home > Backend Development > C++ > How to Resolve 'Multiple Definition of Variable' Errors in C ?

How to Resolve 'Multiple Definition of Variable' Errors in C ?

Susan Sarandon
Release: 2024-11-30 13:10:11
Original
250 people have browsed it

How to Resolve

Multiple Definition of Variable in C

When working with multiple files in C projects, you can encounter errors related to multiple definitions of a variable. Consider the following situation:

FileA.cpp:

#include "FileA.h"

int main()
{
    hello();
    return 0;
}

void hello()
{
    //code here
}
Copy after login

FileA.h:

#ifndef FILEA_H_
#define FILEA_H_
#include "FileB.h"
void hello();

#endif /* FILEA_H_ */
Copy after login

FileB.cpp:

#include "FileB.h"

void world()
{
    //more code;
}
Copy after login

FileB.h:

#ifndef FILEB_H_
#define FILEB_H_

int wat;
void world();


#endif /* FILEB_H_ */
Copy after login

Upon attempting to compile this code, you might encounter an error stating "multiple definition of `wat'."

Explanation:

The error arises because you have defined a global variable, wat, twice in your compilation unit. Both FileA.h and FileB.h include a declaration of wat, defining it twice in the global scope.

Solution:

To resolve this issue, follow these steps:

FileB.h:

extern int wat;
Copy after login

FileB.cpp:

int wat = 0;
Copy after login

By using extern in FileB.h, you inform the compiler that a variable named wat exists somewhere else. In this case, you define the actual variable with an initializer in FileB.cpp.

This approach ensures that wat is declared once in the global scope, eliminating the multiple definition error.

The above is the detailed content of How to Resolve 'Multiple Definition of Variable' 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