1

Assume the following:

test1.h

extern int a;
void init();

test1.c

#include <stdio.h>
#include "test1.h"

int main()
{
    init();
    printf("%d\n", a);
    return 0;
}

test2.c

#include "test1.h"

void init()
{
    int a = 1;
}

Above will give me a linker error saying a isn't defined, but it is defined under init(). However, if I change test2.c like this then it will work:

int a = 1;
void init()
{
    //
}

Does extern have to be defined globally only?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Exactly - only globals can be externals. – VillageTech Dec 25 '19 at 17:48
  • 1
    @VillageTech: Identifiers with local (block) scope can have external linkage. For example, with `#include ` / `int a = 0; int main(void) { extern void foo(void); foo(); printf("%d\n", a); }` in one source file and `void foo(void) { extern int a; a = 4; }`, the program will compile and print “4”. The definition must be a file scope, but the declaration may be inside a block. – Eric Postpischil Dec 25 '19 at 21:35

1 Answers1

0

The internal or external linkage may have only variables that have a file scope.

In your first example

void init()
{
    int a = 1;
}

the variable a has a block scope and hence does not have a linkage.

In the header

extern int a

there is declared a variable with external linkage that has the file scope. But it was not defined. So the linker issues an error because it can not find the variable definition.

You may declare a block scope variable with the extern specifier. But it will not be a variable definition. The declaration will refer to a variable with a linkage declared in a file scope.

For example consider the following demonstrative program

#include <stdio.h>

int x = 10;

void f( void )
{
    extern int x;

    printf( "x = %d\n", x );
}

int main(void) 
{
    f();

    x = 20;

    f();

    return 0;
}

Its output is

x = 10
x = 20

That is there is defined the file scope variable x with the external linkage. And within the outer block scope of the function f the declaration of the variable x refers to the variable x in the file scope. It does not define a new object.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335