Home > Backend Development > C++ > Why Am I Getting Error LNK2005: Multiple Definitions of \'k\' in My Win32 Console Application?

Why Am I Getting Error LNK2005: Multiple Definitions of \'k\' in My Win32 Console Application?

Susan Sarandon
Release: 2024-11-01 00:19:28
Original
526 people have browsed it

Why Am I Getting Error LNK2005: Multiple Definitions of 'k' in My Win32 Console Application?

Error LNK2005: Multiple Definitions of 'k'

When developing a Win32 console application with multiple C source files, you may encounter error LNK2005, indicating that a variable has been defined multiple times.

Cause of the Error

In the given code, both A.cpp and B.cpp define a global variable named 'k'. This violates the C one definition rule, which states that each symbol (function, variable, etc.) must be defined only once in a program.

Resolving the Issue

There are several ways to resolve this error:

1. Using Nameless Namespace (for Variables Needed in Multiple Files)

If you need the same variable in both cpp files, use a nameless namespace to prevent multiple definitions:

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

2. Using 'extern' (for Variables Shared Across Files)

If you need to share a variable across multiple files, declare the variable as 'extern' in the header file and define it in only one cpp file:

<code class="cpp">// A.h
extern int k;

// A.cpp
int k = 0;

// B.cpp
#include "A.h"

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

By following these approaches, you can resolve error LNK2005 and ensure that each symbol is defined only once in your program.

The above is the detailed content of Why Am I Getting Error LNK2005: Multiple Definitions of \'k\' 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template