0

lnk2005 : Linker error with global variable in header and extern

Hi I have a sample header file with pragma once. It just has 1 variable like int x and a print function called display declared. Header is included in cpp file where we just define the function display. header is only included once in main.cpp. In short we have one header having int variable and same is included into two cpp files. header is protected with multiple inclusion using pragma once. I am still getting already defined linker error. This happens as there are two obj files (one due to each of cpp file) and hence linker finds two definitions. Two avoid this issue: 1. declared extern int x in header file 2. define int x in one of the cpp file 2. in other cpp file, neither declare nor define x variable. just use it where ever needed as if it is already defined in first cpp file. Is there any better or at least other way to avoid this issue?

29th May 2024, 3:53 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Respostas
+ 2
you can overcome this issue either with : 1- C++17 inline variables , so you can do: https://godbolt.org/z/xbYE9bTEv 2- unnamed namespace ( same as static, except for its mangled name ) : https://godbolt.org/z/xvGh7dzq1
30th May 2024, 12:39 PM
MO ELomari
MO ELomari - avatar
+ 1
Great..!
31st May 2024, 10:59 AM
Ketan Lalcheta
Ketan Lalcheta - avatar