error LNK2005, already defined?

来源:互联网 发布:win10软件锁怎么设置 编辑:程序博客网 时间:2024/05/20 09:49
I have 2 files A.cpp and B.cpp files in a project "Win32 Console Application".

Both 2 files have only 2 lines following code:

#include "stdafx.h"
int k;

When compiling it threw the error

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


Why this error?

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


Solutions:

one:  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;}
two: If you need to share the same variable across multiple files then you need to useextern

A.h

extern int k;

A.cpp

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

B.cpp

#include "A.h"//Use `k` anywhere in the file 

notice:

In case of extern, k should be defined once in any of the source files.


0 0
原创粉丝点击