Sunday 15 May 2011

c++ - Why linker is giving error for global variable in header file -



c++ - Why linker is giving error for global variable in header file -

i have declared global variable in header.h , included header in source.cpp , main.cpp linker giving error

source.obj : error lnk2005: "int globalvariable" (?globalvariable@@3ha) defined in main.obj globalvariableandlinkageissue.exe fatal error lnk1169: 1 or more multiply defined symbols found header.h int globalvariable; source.cpp #include "header.h" main.cpp #include"header.h" void main() {}

move declaration .cpp file. can utilize declaration in header file using:

extern int globalvariable; // declaration in header - can have many need

but .cpp file should have definition:

int globalvariable; // definition in .cpp - need 1 across files

c , c++ utilize textual pre-processor include headers, text insertion, not smart module scheme in languages. including were, creating multiple definitions, 1 per .cpp file.

as matter of practice, need used using include guards protect against multiple nested includes (though not solve current issue). if using visual c++, can utilize #pragma once or utilize portable solution wrap header code in:

#ifndef _include_foo_h_

#endif

c++ linker extern

No comments:

Post a Comment