Re: extern for global variable: C Question
- From: "Leslie Milburn" <CDB4W@xxxxxxxxxxxxxxxxxx>
- Date: Sat, 19 Dec 2009 18:58:38 +1000
"Robby" wrote:
Hi Robby,
I am not a fan of global variables at all. To use them is a last resort as
it implies a code design problem. In all my 25+ years of C programming I
have hard ever had to resort to using a global variable. I suggest you look
at the code once more and decide if the variable could be passed as a
parameter as needed.
Objective:
The data in the MQ array has to be accessible and available in many
functions of several .c files, and therefore should appear to have global
scope.
I disagree, pass the variable as a parameter to the functions that require
access to the variable. Yes *all* of them.
Resolution:
As shown in code above, I declared an array as "extern" and then defined
it
in one .c file and where ever other .c files require access to MQ[], I
have
to include the KERNEL.h file. Is this an okay practice to do with all
other
global variables, arrays and arrays of structures?
I have seen some programmers follow this approach. IMO over time the code
may become harder to read and you need to consider if any programmers other
than yourself will be maintaining the code. I always assume (even for my
private projects) that I will not be the only programmer reading the code.
My preferred approach is to declare the variable at the top of the .c module
in which it is first created and usually (but not always) populated. Then
for each .c module that requires access to the variable I place "extern
variable name" at the top of that module with a comment indicating why I am
using it. To make the code more readable I use the naming convention of
modulename_variablename to help identify where the declaration is located.
So in your case it would be api_MQ.
Of concern is that your choice of module name and variable names are not
really that meaningful. api.c and kernel.c are not useful names if you think
about it. Which API is api.c referring to. Also MQ also has little meaning.
Before you get to far down the road you might like to revisit your naming
conventions. My main software project comprises of approximately 400 .c
modules and it is easy to forget the finer details when you revisit code 12
to 18 months later. So trust me when I say you will be thankful you used
meaningful names.
hth
leslie.
.
- Follow-Ups:
- Re: extern for global variable: C Question
- From: Robby
- Re: extern for global variable: C Question
- From: Tim Roberts
- Re: extern for global variable: C Question
- References:
- extern for global variable: C Question
- From: Robby
- extern for global variable: C Question
- Prev by Date: Re: extern for global variable: C Question
- Next by Date: Re: extern for global variable: C Question
- Previous by thread: Re: extern for global variable: C Question
- Next by thread: Re: extern for global variable: C Question
- Index(es):
Relevant Pages
|