Home > Backend Development > C++ > body text

Why am I getting the \'error LNK2005: already defined?\' error when I define the same variable in multiple C files?

Patricia Arquette
Release: 2024-10-30 01:43:29
Original
837 people have browsed it

Why am I getting the

Error: "error LNK2005: already defined?"

In your console application, you've encountered an unexpected error while compiling files A.cpp and B.cpp. Both files contain the following code:

#include "stdafx.h"
int k;
Copy after login

However, the compilation process generates an error:

Error 1 error LNK2005: "int k" (?a@@3HA) already defined in A.obj
Copy after login

This error stems from the violation of the "one definition rule." In C , each variable, function, and object can only be defined once. In your case, you've defined the variable "k" in both A.cpp and B.cpp.

Solutions

Using Nameless Namespace

If you'd like to use the same named variable in both files, you can utilize a nameless namespace (anonymous namespace) to avoid the conflict.

namespace
{
    int k;
}
Copy after login

By encapsulating "k" within a namespace, you effectively limit its scope to the respective files, preventing the definition error.

Using External Declaration

If you intend to share the "k" variable across multiple files, you can employ the technique of external declaration and definition:

A.h (header file)

extern int k;
Copy after login

A.cpp

#include "A.h"
int k = 0;
Copy after login

B.cpp

#include "A.h"

// Use 'k' variable as needed
Copy after login

In this scenario, you declare a variable as external in A.h and define it in A.cpp. The B.cpp file only needs to include A.h to access the variable, avoiding the definition conflict.

The above is the detailed content of Why am I getting the \'error LNK2005: already defined?\' error when I define the same variable in multiple C files?. 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