error LNK2005, already defined?

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 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 

notice:

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


你可能感兴趣的:(C++编程)