Home > Backend Development > C++ > body text

Why am I Getting \'error LNK2005: already defined\' in my C project?

Susan Sarandon
Release: 2024-11-02 11:16:02
Original
551 people have browsed it

Why am I Getting

Unveiling the Mystery of Error LNK2005: Understanding Multiple Definitions

When working with multiple C files within a project, the "error LNK2005, already defined" message can be a perplexing hindrance. This error signifies that multiple definitions of the same variable or function exist within the project. To delve into this issue, let's examine a specific example.

The Problematic Scenario

Consider a Win32 console application comprising two files: A.cpp and B.cpp. Both files contain only the following:

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

Upon compilation, the error arises:

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

The Root of the Problem: Violating the One Definition Rule

The fundamental principle underlying this error is the "one definition rule" (ODR) enforced in C . This rule dictates that any variable or function can only have one definitive definition throughout the entire project. In this scenario, both A.cpp and B.cpp attempt to define the same variable 'k', violating the ODR. As a result, the linker encounters a conflict and triggers the error message.

Addressing the Issue

To resolve this error, you can employ two primary approaches:

Approach 1: Utilizing Nameless Namespaces

If your intention is to share the same variable across multiple translation units (i.e., cpp files), consider utilizing a nameless namespace. A nameless namespace encapsulates the variable within its own scope, rendering it inaccessible outside that scope.

namespace {
    int k;
}
Copy after login

Approach 2: External Variables

Alternatively, if you need to share a variable across multiple files but want to maintain its accessibility to external code, employ the 'extern' keyword. This approach involves declaring the variable in a header file (e.g., A.h):

extern int k;
Copy after login

and subsequently defining it in one of the implementation files (e.g., A.cpp):

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

The above is the detailed content of Why am I Getting \'error LNK2005: already defined\' in my C project?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!