3

I was reading a C reference about linkage (external, internal and none) and came across the following:

If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

I wanted to know how this undefined behavior can occur. Based on what I had read, a variable can have only one storage class. So it cannot be declared both static and extern at the same time.

So in what scenario can a variable have both internal and external linkage?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Abhay Aravinda
  • 878
  • 6
  • 17
  • 1
    Well, you can declare the same function multiple times; and you have the definition vs the declaration. Maybe that's the intention? Just speculating, IANALL. – einpoklum Sep 05 '20 at 18:03

1 Answers1

2

In this code:

extern int x;
static int x;

The first declaration says x has external linkage, and the second declaration says it has internal linkage.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Just wanted to clarify. It doesn't compile if I put both `extern int x` and `static int x` in the same scope. It compiles if I declare a static global variable and use the extern keyword inside `main()`. Is that what you meant? – Abhay Aravinda Sep 06 '20 at 05:56
  • Sorry. It does compiles if I declare it static first and then extern (both declared in global scope). Thanks for the answer – Abhay Aravinda Sep 06 '20 at 06:11
  • @AbhayAravinda: `extern` and `static` have different effects depending on where they appear. If an identifier is declared `extern` after an earlier declaration with internal or external linkage, the new declaration just copies the old; it will not change a declaration with internal linkage to external. (If the earlier declaration specifies no linkage, the new declaration makes a new identifier with external linkage.) If an identifier is declared with `static` in block scope, it has no linkage. – Eric Postpischil Sep 06 '20 at 10:26
  • So `extern int x; static int x;` gives `x` two linkages, violating the rules, since the first declaration has external linkage. But `static int x; extern int x;` does not violate the rules, since the second declaration leaves the internal linkage. – Eric Postpischil Sep 06 '20 at 10:27