Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why linker is giving error for global variable in header file

Tags:

c++

extern

linker

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() {}
like image 558
Maddyfire Avatar asked Jan 24 '26 04:01

Maddyfire


1 Answers

  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

like image 162
codenheim Avatar answered Jan 26 '26 17:01

codenheim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!