3

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!

winuall
  • 359
  • 1
  • 5
  • 13

3 Answers3

7

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;
}
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • 2
    'extern' can also be used when with variables. A good writeup of the whys/hows are here: http://stackoverflow.com/questions/1433204/what-are-extern-variables-in-c – gdc Mar 28 '12 at 18:04
  • @gdc +1, and more important: on variables this keyword is not redundant, so this is the main use. – asaelr Mar 28 '12 at 18:07
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

stefan bachert
  • 9,413
  • 4
  • 33
  • 40
0

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.

asaelr
  • 5,438
  • 1
  • 16
  • 22