Reputation: 981
Most explanations that I come across describing why the static keyword is used on global functions or variables describe its effect as the following: "The static-marked function or variable in the global scope is not visible to files(more specifically, compilation units) outside where they are defined". Given that static functions specifically are seldom used in .h files other than in combination with inline, I ask: Why do we need to mark functions and variables in .c files as static when such .c file is never included into any other compilation unit, thus defeating the purpose of marking functions static so as to make them "not visible" in other compilation units?
Upvotes: 2
Views: 174
Reputation: 6659
Consider:
// a.c
static void f(void) {...}
void DoIt(void) {...}
and
// b.c
static void f(void) {...}
void DoIt(void) {...}
Now the compiler generates object files from each of those source files without ever knowing that there's a name collision. The void f(void)
signatures are hidden from the linker when a
and b
are linked into a program, because the static keyword limits them to file scope, but it can see two void DoIt(void)
signatures because they are both at global scope. Now consider:
// c.c
extern void DoIt(void);
static void f(void)
{
DoIt(void); // Which implementation should be called here?
}
Just because you never wrote a header file with your function name in it, doesn't mean that you or some programmer won't try using that symbol name somewhere else. Using static, limits the name pollution in the global scope, so hopefully, you don't encounter too many collisions.
Another reason we hide symbol names in file scope, is to make it difficult for other programmers to use functions we do not intend for them to be using. Every symbol you expose at global scope is a potential support call. It can make it very difficult for you to refactor or otherwise modify your code, if you have hundreds of products/developers out there who have dependencies on your internal bits. By hiding it from them at file scope, you are saying "I will not support you taking dependencies on these symbols", so if they go ahead and do it anyway, they have no right to complain when you remove them or modify how they are used by your code.
Upvotes: 4