In C, when stating extern
or static
specifiers on a function, what is the proper syntax use -
only on declaration? on definition? both? is it the same with a variable?
Thanks!
In C, when stating extern
or static
specifiers on a function, what is the proper syntax use -
only on declaration? on definition? both? is it the same with a variable?
Thanks!
Declaring a extern
Function:
The keyword extern
should be used only while declaring(not defining) a function.Note that functions by default have external linkage so the keyword extern
on a function declaration is redundant.
extern void doSomething();
Defining a extern
Function:
The function definition should not be specified with extern
keyword. The definition could be in another cpp file.
void doSomething()
{
}
Declaring a static
Function:
A static
function restricts the use of the function to the Translation Unit in which it is declared. You need to specify the keyword when you declare it.
static void doSomething();
Defining a static
Function:
The function definition needs to be defined in the same TU.You don't need to specify the static
keyword while defining it.
void doSomething()
{
}
Using a extern
variable:
You declare a variable as extern
when you want to share the same global variable accross different translation Unit.
You need to declare the variable with extern
keyword while you need to define it in one and only one cpp file.
file1.h
extern int i;
file1.cpp
#include"file1.h"
int i = 10;
file2.cpp
#include "file1.h"
int main()
{
i = 40;
return 0;
}
stuff defined with static belongs to the current compilation unit (module). Such stuff are NOT seen outside the unit
extern declares something which is somewhere else defined
I don't know what do you mean in the words on call
, but I assume you want to ask about definition
and declaration
.
The keyword extern
means "This variable/function is defined somewhere else", so it's meaningless to use it on definition. You should use it only on declaration.
The keyword static
(on functions and global variables) mean "don't export this symbol", You should write it on the first declaration (or definition) of the symbol.