1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Rep Power

    Global variables

    for this code, the compiler is telling me that str is undefined.
    #include <stdio.h>
    #include <string.h>
    extern char str[LEN];
    void something(void);
    int main()
    void something(void)
    Didn't I define it as a global variable?
    Does it have something to do with the fact that memory is not allocated for an extern declaration?
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Rep Power
    > Didn't I define it as a global variable?
    No, you declared one.

    > Does it have something to do with the fact that memory is not allocated for an extern declaration?

    Now look up "declaration vs. definition" in your book, or online.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Rep Power
    You declared str as an extern. By that you are telling the compiler that somewhere out there is this char array called str. This gives the compiler all the information it needs to work with str, except for its actual location, but extern tells the compiler that it can safely leave that to the linker, so it marks its usage of str as needing to be resolved by the linker. Then when the linker tries to resolve that address, it finds that you never did define str, so it complains loudly.

    OBTW, you also did not #define LEN.

    Common practice is to keep all externs in header files and then choose logical source files to define them in. That will almost create a check-list in your mind that helps you take care of everything. Normally, I will first define the global in the source file that creates and initializes it (that being the "logical choice") and add its extern to the header file. For example, some of our products use a GPS receiver, so we have one source file that is dedicated to communicating with the GPS receiver and maintaining a database of information that we get from the GPS receiver. Part of that database is an array of satellite data, so I define that array in the source file and then copy its extern into that source file's header file for all the other source files that reference that array. Yes, you can add a single extern to your source file, but that should be the exception to the rules of your common practices.

    Comments on this post

    • eramit2010 agrees : :)

IMN logo majestic logo threadwatch logo seochat tools logo