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
Susan SarandonOriginal
2024-11-30 13:10:11176browse

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
}

FileA.h:

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

#endif /* FILEA_H_ */

FileB.cpp:

#include "FileB.h"

void world()
{
    //more code;
}

FileB.h:

#ifndef FILEB_H_
#define FILEB_H_

int wat;
void world();


#endif /* FILEB_H_ */

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;

FileB.cpp:

int wat = 0;

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!

Statement:
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
Previous article:Debug and run on Win32Next article:Debug and run on Win32