Home > Backend Development > C++ > body text

Why Am I Getting \'Error LNK2005: \'int k\' Already Defined\' in My Win32 Console Application?

DDD
Release: 2024-10-30 08:39:27
Original
920 people have browsed it

Why Am I Getting

Error LNK2005: "int k" Already Defined

When linking a Win32 console application with multiple C files, an error "error LNK2005: "int k" (?a@@3HA) already defined in A.obj" may arise. This error occurs when a variable with the same name is defined in multiple files.

In the given example, both A.cpp and B.cpp define a variable k. According to the one definition rule, each global variable or function must have a single definition. Having multiple definitions leads to ambiguity and linking errors.

Solutions:

To resolve this error, you can use the following approaches:

Use Nameless Namespace (Anonymous Namespace):

If the variable k is intended to be private to each file, use a nameless namespace to prevent the symbol name collision.

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

This isolates the symbol k within each file, preventing other files from accessing or redefining it.

Declare and Define Variable in Separate Files:

If you need to share the variable k across multiple files, use extern to declare it in the header file and define it in a separate compilation unit.

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` anywhere in the file</code>
Copy after login

By declaring k as extern in the header file, other files can access and use it without redefining it.

The above is the detailed content of Why Am I Getting \'Error LNK2005: \'int k\' Already Defined\' 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!