Home > Backend Development > C++ > body text

Why am I getting the \'Error LNK2005: Multiple Definitions\' error in my Win32 console application?

DDD
Release: 2024-10-31 00:45:02
Original
851 people have browsed it

Why am I getting the

Error LNK2005: Multiple Definitions

In a Win32 console application, you have two source files, A.cpp and B.cpp, each containing the following code:

<code class="cpp">#include "stdafx.h"
int k;</code>
Copy after login

Upon compilation, an error is encountered:

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

Explanation:

This error stems from violating the one definition rule. In C , every global variable or function can only have a single definition across all translation units (source files). In your case, both A.cpp and B.cpp define the variable k, leading to multiple definitions and the linking error.

Solutions:

To resolve this issue, consider the following options:

1. Using Anonymous Namespace:

If you require the variable k to be used within both A.cpp and B.cpp but want to avoid external linkage, you can utilize an anonymous namespace:

<code class="cpp">namespace 
{
    int k;
}</code>
Copy after login

2. Using extern:

If you need to share the variable k across multiple files, you should declare it as extern in a header file (A.h) and define it in one source file (e.g., A.cpp):

A.h

<code class="cpp">extern int k;   </code>
Copy after login

A.cpp

<code class="cpp">#include "A.h"
int k = 0;</code>
Copy after login

B.cpp

<code class="cpp">#include "A.h"

// Use `k` within B.cpp</code>
Copy after login

By following these solutions, you can avoid multiple definitions of k and successfully compile your application.

The above is the detailed content of Why am I getting the \'Error LNK2005: Multiple Definitions\' error in my Win32 console application?. 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
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!