Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error LNK2005, already defined?

Tags:

c++

I have 2 files, A.cpp and B.cpp, in a Win32 console application.

Both 2 files contain only the following 2 lines of code:

#include "stdafx.h" int k; 

When compiling it produces the error

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

I don't understand what is happening.

Can someone please explain this to me?

like image 774
TTGroup Avatar asked Apr 06 '12 16:04

TTGroup


2 Answers

Why this error?

You broke the one definition rule and hence the linking error.

Suggested Solutions:


If you need the same named variable in the two cpp files then You need to use Nameless namespace(Anonymous Namespace) to avoid the error.

namespace  {     int k; } 

If you need to share the same variable across multiple files then you need to use extern.

A.h

extern int k; 

A.cpp

#include "A.h" int k = 0; 

B.cpp

#include "A.h"  //Use `k` anywhere in the file  
like image 194
Alok Save Avatar answered Oct 19 '22 07:10

Alok Save


In the Project’s Settings, add /FORCE:MULTIPLE to the Linker’s Command Line options.

From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."

like image 30
Michael Haephrati Avatar answered Oct 19 '22 07:10

Michael Haephrati