Maddyfire
Maddyfire

Reputation: 61

Why linker is giving error for global variable in header file

I have declared a global variable in header.h and included that header in source.cpp and main.cpp but linker is giving error

Source.obj : error LNK2005: "int globalVariable" (?globalVariable@@3HA) already defined in     Main.obj
GlobalVariableAndLinkageIssue.exe fatal error LNK1169: one or more multiply defined symbols found

header.h

int globalVariable;

source.cpp

#include "header.h"

main.cpp

#include"header.h"

void main() {}

Upvotes: 3

Views: 2096

Answers (5)

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

Put global variable in some .c or .cpp file, so that it can be defined only once and refer in header file using extern for example,

header.h

extern int globalVariable;

header.cpp

int globalVariable = 0;

source.cpp

#include "header.h"

main.cpp

#include"header.h"

int main() {
  return 0;
}

Upvotes: 1

Ron Pinkas
Ron Pinkas

Reputation: 367

In such situation,it is common to use some #define as follows:

//header.h
#ifdef DEFINE_VARS
   #define DEFINE_OR_DECLARE 
#else
   #define DEFINE_OR_DECLARE extern
#endif

DEFINE_OR_DECLARE int globalVariable;


//main.cpp
#define DEFINE_VARS
#include "header.h"
...

//header.cpp
#include "header.h"
...

Upvotes: -2

mrjoltcola
mrjoltcola

Reputation: 20842

  1. Move the declaration to a .cpp file. You can use a declaration in a header file by using:

    extern int globalVariable; // declaration in header - can have as many as you need

    But the .cpp file should have the definition:

    int globalVariable; // definition in .cpp - only need one across all your files

    C and C++ use textual pre-processor to include headers, this is basically a text insertion, not a smart module system as in some languages. By including it as you were, you are creating multiple definitions, one per .cpp file.

  2. As a matter of good practice, you need to get used to using include guards to protect against multiple nested includes (though it would not solve your current issue). If using Visual C++, you can use #pragma once or to use a portable solution wrap your header code in:

    #ifndef _INCLUDE_FOO_H_

    #endif

Upvotes: 3

Ron Pinkas
Ron Pinkas

Reputation: 367

Because BOTH sources #include your header, and thus it is DEFINED twice.

Upvotes: 0

Bill Lynch
Bill Lynch

Reputation: 81916

To create a global variable, you should do the following. Note that in the header, we mark the variable as extern, and we actually create the object in a cpp file.

header.h

extern int globalVariable;

header.cpp

#include "header.h"
int globalVariable;

main.cpp

#include "header.h"

int main() {}

Upvotes: 1

Related Questions