Wednesday, August 5, 2009

extern/static in function declaration

I have never really paid attention to the 'extern' keyword in a function declaration, so here is my understanding of this.

In C:

In the simplest form, the 'extern' keyword changes the linkage so that the resolving is deferred to the linker. It is assumed that the function is defined/available somewhere else.

Whereas a 'static' keyword when declaring a function, it makes the function local to that file.

I suppose if you don't use the extern/static keyword when declaring the function, it defaults to extern.

static c variables are of course different than non-static variables.

In C++:

'static' functions in C++ have a very different usage. A static member function of a class is generally called without having to instantiate an object of the class. This is same for the static member variables of the class as well.

The static functions do have their limitations:

  • A static member function can access only static member data, static member functions and data and functions outside the class.
  • A static member function cannot be declared virtual, whereas a non-static member functions can be declared as virtual.
  • A static member function cannot have access to the 'this' pointer of the class.

No comments: