On May 5, 4:53 am, "Bartc" <b...@[EMAIL PROTECTED]
> wrote:
> I noticed that in C, functions in any module are automatically ex****ted.
So
> that it's not possible to use the same function name in two modules (ie.
> source files).
>
> Now that I know that, I get work around it; but is there a way to avoid
the
> problem (short of lots of renaming)?
>
Declare the items you want to keep "private" static:
/** myfile.c */
/**
* The following variable and function cannot be
* referred to by name outside of myfile.c; however,
* they can still be referred to using pointers returned
* from other functions within the file.
*/
static int x;
static void foo() {...}
> More seriously, variables declared at file scope also seem to be
> automatically ex****ted. But in this case, the compiler/linker doesn't
warn
> me that the same name is being used in two or more modules. (Is this
what
> the fuss is about with 'global variables'?)
>
The compiler will attempt to resolve multiple declarations of the same
variable into a single entity according to one of several models. The
key thing is that only one declaration can be a *defining*
declaration, and all the rest are *referencing* declarations. There
are several models by which the compiler determines which is a
defining vs. referencing declaration. Anything with an initializer is
considered a defining declaration; if you had two declarations with
initializers, and the initializers were different values, you would
get a diagnostic.
The problem with globals is that they promote tight coupling between
modules, discouraging code reuse. For example, if you had a sorting
routine that relied on the presence of a global variable to indicate
the array size, you could not reuse that routine in a program that did
not define that global.
> Is there any way I can fix this? (Like some keyword that will render a
> variable local to a module.)
>
> -- Bartc
Like I said, use the static qualifier for each item you don't want
ex****ted. Remember that doing so only prevents other modules from
referring to those entities by name; there's nothing preventing you
from writing a function to return a pointer to a static item, thus
making it available to other modules by reference. But it at least
allows you to reuse names.


|