Re: extern const int n; considered undefined reference?
Jim Michaels wrote (command prompt shortened):
d:\prj\lib\prsinum\test|>g++ -Wextra -Wall -o m.exe i.cpp m.cpp
C:\Users\JIM-MI~1\AppData\Local\Temp\ccQU9nKz.o:m.cpp:(.text+0x17):
undefined reference to `n'
collect2.exe: error: ld returned 1 exit status
d:\prj\lib\prsinum\test|>type i.cpp
const int n=5;
d:\prj\lib\prsinum\test|>type i.h
extern const int n;
d:\prj\lib\prsinum\test|>type m.cpp
#include "i.h"
#include <iostream>
int main(void) {
std::cout<<n;
return 0;
}
d:\prj\lib\prsinum\test|>
why can regular variables be extern'd but not const versions of same?
I would like to import them in a header somehow. but my practices seem
to be failing for an unknown reason.
bad practice? gcc bug? please let me know. I don't have the BNF for
c++11 handy to look at to check against.
By default, objects declared const have internal linkage. When i.cpp is
compiled, the compiler only sees 'const int n=5;', and so it concludes
that n has internal linkage. The result is equivalent to 'static const
int n=5;': n's definition is hidden from other translation units (source
files).
The obvious fix is to include i.h in i.cpp. Now, the compiler will
first see 'extern const int n;' before 'const int n=5;', and give n
external linkage, making it available to other translation units.
In general, a source file that contains the definition of a function or
object that is intended to be externally visible (in this case, the
'const int n=5;' in i.cpp) should include the header file that
contains the corresponding declaration (in this case, the 'extern
const int n;' in i.h). This results in consistent linkage and gives
the compiler a chance to detect any other mismatches.
- Wil
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]