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