Extern variables and linking

Discussion in 'C++' started by Dave, Dec 2, 2003.

  1. Dave

    Dave Guest

    Why does the program below link successfully? (Yep, what's shown is all
    there is to it.) Does an extern variable actually have to be referenced to
    be bound to an address? Is this Standard-compliant behavior?


    int main()
    {
    extern int a;
    }
     
    Dave, Dec 2, 2003
    #1
    1. Advertising

  2. Dave wrote in news::

    > Why does the program below link successfully? (Yep, what's shown is
    > all there is to it.) Does an extern variable actually have to be
    > referenced to be bound to an address?


    Sorry that last sentence just doesn't parse.

    > Is this Standard-compliant behavior?


    Yes.

    >
    >
    > int main()
    > {
    > extern int a;


    You're telling the compiler such an object 'a' exists, but since you
    *never* reference it the compiler never uses the information. If this
    wern't the case including headers would link huge amounts of unused
    code and data (just so the optimizer can throw it all away again :).

    Try adding:

    a = 1;

    > }
    >


    Rob.
    --
    http://www.victim-prime.dsl.pipex.com/
     
    Rob Williscroft, Dec 2, 2003
    #2
    1. Advertising

  3. Dave wrote:

    > Why does the program below link successfully?
    > (Yep, what's shown is all there is to it.)
    > Does an extern variable actually have to be referenced
    > to be bound to an address?
    > Is this Standard-compliant behavior?
    >
    > int main() {
    > extern int a;
    > }



    > cat main.c

    int main(int argc, char* argv[]) {
    extern int a;
    return 0;
    }

    > g++ -Wall -ansi -pedantic -c main.c

    main.c: In function `int main(int, char**)':
    main.c:2: warning: unused variable `int a'
    > nm main.o

    00000000 T main



    > cat main.c

    int main(int argc, char* argv[]) {
    extern int a;
    return a;
    }

    > g++ -Wall -ansi -pedantic -c main.c
    > nm main.o

    U a
    00000000 T main
     
    E. Robert Tisdale, Dec 2, 2003
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Thomas Matthews
    Replies:
    5
    Views:
    2,439
    tom_usenet
    Aug 2, 2004
  2. Bill Nolan

    extern var's and linking

    Bill Nolan, Dec 30, 2004, in forum: C++
    Replies:
    1
    Views:
    892
    Victor Bazarov
    Dec 30, 2004
  3. iwl
    Replies:
    3
    Views:
    660
  4. Stanley Rice

    linking problem? | extern keyword

    Stanley Rice, Nov 14, 2011, in forum: C Programming
    Replies:
    6
    Views:
    328
    James Kuyper
    Nov 15, 2011
  5. Andre
    Replies:
    5
    Views:
    542
    Keith Thompson
    Jul 17, 2012
Loading...

Share This Page