From what I already know, both global non-constant variables and functions have external linkage by default. So they can be used from other files with the help of forward declaration . For example:
<other.cpp>
int myNum{888};
int getAnInt()
{
return 999;
}
<main.cpp>
#include <iostream>
extern int myNum; // "extern" keyword is required.
int getAnInt(); // "extern" keyword is NOT required.
int main()
{
std::cout << getAnInt() << "\n";
std::cout << myNum << "\n";
}
However, if no extern
before int myNum;
. This will happen:
duplicate symbol '_myNum' in:
/path~~/main.o
/path~~/other.o
ld: 1 duplicate symbol for architecture x86_64
So my question is why extern
is required for myNum
? Don't global non-constant variables have external linkage by default?