July 21st, 2013, 01:40 AM
for this code, the compiler is telling me that str is undefined.
Didn't I define it as a global variable?
extern char str[LEN];
Does it have something to do with the fact that memory is not allocated for an extern declaration?
July 21st, 2013, 02:06 AM
> 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.
July 21st, 2013, 01:20 PM
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