What is the correct use of external and static?
Function declaration extern
:
The keyword extern
should only be used when declaring (not defining) a function. Note that functions are externally linked by default, so the keyword extern
in the function declaration is redundant.
extern void doSomething();
Function definition extern
:
A function definition should not be specified with a keyword extern
. The definition can be in another cpp file.
void doSomething()
{
}
Function declaration static
:
Function A static
restricts the use of the translation units function in which it is declared. You need to provide the keyword when you declare it.
static void doSomething();
Function definition static
:
A function definition must be defined in the same TU. You don't need to include a keyword static
when defining it.
void doSomething()
{
}
Variable Usage extern
:
You declare a variable as extern
when you want to use the same global variable in different translation units. You need to declare a variable with a keyword as extern
long as 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;
}
source to share
I don't know what you mean in words on call
, but I am assuming you want to ask about definition
and declaration
.
The keyword extern
means "This variable / function is defined somewhere else", so it makes no sense to use it in the definition. You should only use it when declaring.
The keyword static
(by functions and globals) means "do not export this symbol", you must write it in the first declaration (or definition) of a symbol.
source to share
Just add ... static indicates that the function or data item is known only within the scope of the current compilation. In addition, if you use the static keyword with a variable that is local to a function, it allows you to keep the last value of the variable between successive calls to that function.
source to share