Reputation: 34608
I have a two C files.
file1.c
int main()
{
func();
return 0;
}
file2.c
static void func(void)
{
puts("func called");
}
But, if I compile the above code with command cc file2.c file1.c
, I got the below,
undefined reference to `func'
collect2: error: ld returned 1 exit status
But, If I remove static
keyword inside file2.c and compile the above code with command cc file2.c file1.c
, It's succesfully run.
So, I have a question, What is the difference between void and static void function in C?
Upvotes: 29
Views: 87160
Reputation: 17668
What is the difference between void and static void function in C?
The real question should be what is the difference between static
and non-static
function? (the return type void
is irrelevant, it can be int
or anything else).
The static
keyword is somewhat over used. When it applies to function, it means that the function has internal linkage, ie its scope is limited to within a translation unit (simply as a source file).
By default, function is non-static and has external linkage. The function can be used by a different source file.
In your case, the error manifests itself because static func
cannot be used in other source file.
When should static
functions be used?
static
functions are normally used to avoid name conflicts in bigger project. If you inspect Linux kernel source, example in drivers/net
you would see many static void
functions in there. Drivers are developed by different vendors and the usage of static
functions ensure that they can name the functions the way they want without worrying of name conflicts with other non-related driver developers.
Upvotes: 60