Stephen Jacob
Stephen Jacob

Reputation: 901

Extern and Linker Error

Why do variables need to be externed at declaration in header file and then declared again in the corresponding cpp file to:

a. Prevent Link error

    ex. header 1.h-
    namespace forglobal { 
    extern int x;
    }

     source 1.cpp- 
    namespace forglobal{
    int x=6;
    }

    source 2.cpp- 
    #include "1.h"
    cout<<x; //6

b. Use in different cpp files, can't I just use the namespace like I call a function ex.

    header -1.h
    namespace forglobal {
    int x
    }

    source -1.cpp {
    namespace forglobal {
    void change() {
    x=5;
    }
    }
    }

    source -2.cpp 
    #include "1.h"
    forglobal::change();
    cout<<forglobal::x<<'\n'; //5

Upvotes: 1

Views: 5017

Answers (3)

CS Pei
CS Pei

Reputation: 11047

This question is related to one fundamental concept in C++ which is One Definition Rule (ODR). As Dietmar Kühl said, without "extern", you have multiple definitions of the same variable which will violate ODR.

However, in C++ you can have as many declarations as possible. Basically declaration introduces a name into scope and definition allocates some memory for a variable.

Please refer to the book by Bjarne Stroutstrup, "The C++ Programming language".

Upvotes: 1

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153802

Any namespace-level variable declaration which isn't declared extern is also a definition. That is, if you have header with a non-extern variable declaration which is included in more then one translation unit linked into a program, you get multiple definitions. To prevent that, you mark the variable declaration in the header as extern and omit the extern where the definition is located.

Of course, using global variables is generally a Bad Idea in the first place but that's a different discussion.

Upvotes: 1

Jiminion
Jiminion

Reputation: 5168

In the second case, you are allocating space for the variable x in two places, so the linker wouldn't know how to access the variable. In the former, only one place is allocated, so there is no confusion.

Upvotes: 0

Related Questions