Click here to Skip to main content
15,881,516 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
So, i'm using Visual Studio 2019, C++ language.
Why does the linker give me error "unresolved external symbol" in this case?

main.cpp
C++
const int myAge = 70;

secondFile.cpp
C++
extern const int myAge;


What I have tried:

Without "const" it links fine.
Also these two variants of secondFile.cpp link successfully which doesn't make any sense to me:
secondFile.cpp
C++
const int myAge = 30;  // isn't it a duplicate symbol? Without "const" it is a a duplicate symbol!

secondFile.cpp
C++
extern const int myAge = 25; // well, it links fine but what's the point of "external" then? We can't access "myAge" from "main.cpp"! 
Posted
Updated 14-Feb-21 18:51pm
v4
Comments
Rick York 6-Dec-20 16:54pm    
Doing this kind of thing is very bad practice. You should always avoid having constant values defined in multiple places. A better way to do this is to define the value once in a header file, without the extern.
Avtem 7-Dec-20 7:57am    
But that is the point of my question. i wanted to define the variable only once and use it in all files. But i like the way you propose to achieve result i need.

Storage class specifiers - cppreference.com[^]

Names at the top-level namespace scope (file scope in C) that are const and not extern have external linkage in C, but internal linkage in C++.


So solution to your problem would be:

// main.cpp
extern const int myAge = 70;

// secondFile.cpp
extern const int myAge;
 
Share this answer
 
Comments
Avtem 6-Dec-20 13:33pm    
Oh, it's interesting! i need to expand my knowledge about c++ in this direction)
Thank you very much for your answer!
Avtem 20-Jul-22 8:51am    
For those, who find difficult to understand cppreference i strongly recommend this site for learning C++: After i read the article i was knowing and understanding anything from this topic:
https://www.learncpp.com/cpp-tutorial/sharing-global-constants-across-multiple-files-using-inline-variables/
The way correct, but sharing variables isnt a good idee. Better is to code some setter und getter interfaces between the files or better classes.
If you need a lot of data, than it is best to create some data providing class aka "Repository" which has a such global instance aka "SharedInstance".

Global variables are a hint to a bad design, which will lead to nasty bugs.
 
Share this answer
 
Comments
Avtem 6-Dec-20 13:56pm    
Thank you for pointing that out. Definitely something i have to work on)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900