1

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?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Jaxon
  • 164
  • 9
  • 6
    because `extern` turns variable definition into declaration, while `int getAnInt();` is already a declaration. You are allowed to have multiple declarations (as long as they are identical), but only one definition for each entity. – SergeyA Aug 19 '20 at 21:19

1 Answers1

2

Because there is a difference between

int getAnInt(); 

and

int getAnInt() { ... }

Namely the brackets themselves, and as such there is no need for a marker like extern to differentiate between the two.

Particularly, the former is a declaration, which just states that getAnInt exists and returns an int etc, whereas the latter gives it its definition.

Hi - I love SO
  • 615
  • 3
  • 14