I'm confused about why I need extern
or not for int
vs char*
in the definition in my extern.cpp file. I have the following test program:
// extern.cpp
extern const int my_int = 1;
const char* my_str = "FOO";
// main.cpp
#include <iostream>
extern const int my_int;
extern const char* my_str;
int main() {
std::cout << my_int;
std::cout << my_str;
return 0;
}
If I remove the extern
from extern const int my_int = 1;
then I get undefined reference to 'my_int'
. If I add extern to const char* my_str = "FOO";
then I get a warning 'my_str' initialized and declared 'extern'
. Why do I need extern
on my_int
but adding it to my_str
generates a warning?
This is C++17 on gcc 10.1.0. The specific commands are:
/usr/bin/g++-10 -g -std=gnu++17 -o main.cpp.o -c main.cpp
/usr/bin/g++-10 -g -std=gnu++17 -o extern.cpp.o -c extern.cpp
/usr/bin/g++-10 -g main.cpp.o extern.cpp.o -o TestExtern
my_str
is notconst
– Adolfoadolphconst
has issue withextern
– Taintlessextern
is never intended to be used with initialization. Useextern
in header files and then in somec
orcpp
file define the actual variable, without usingextern
. Theextern
declaration from the header file can be in scope and its types will have to match. – Coonhoundmy_str
toconst char * const my_str
then you will have the same issue. – Taintlessconst
not aboutextern
. – Dissonanceconst
when applied to a pointer. But Andrey deals with this point below, so I guess it doesn't matter. – Dissonance