Home  >  Article  >  Backend Development  >  Why Am I Getting \"Error LNK2005: \"int k\" Already Defined\" in My Win32 Console Application?

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

DDD
DDDOriginal
2024-10-30 08:39:27919browse

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>

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>

A.cpp

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

B.cpp

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

// Use `k` anywhere in the file</code>

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!

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