Wednesday, January 30, 2008

Controlling linkage, static keyword

Was asked before and I thought I was clear.
#include "Car.hpp"
int a = 2;

int main()
 return 0;
// following is Car.cpp file, Car.hpp includes declear
#include "Car.hpp"
extern int a;
void foo()
 printf ("%d\n",  a);

the visibility of a is global across all translation units. But if you say instead:

static int a = 2;

all you’ve done is change the visibility, a can only be seen in main file. Compile error happens. Look at the following two functions:

extern void foo();
static void foo();

The first one is the same as the unadorned declaration. The 2nd one means foo() is visible only within this translation unit – this is sometimes called file static.
External linkage & Internal linkage
Ordinarily, any name at file scope is visible throughout all translation units in a program. This is often called external linkage because at link time the name is visible to the linker everywhere.

An object or function name at file scope that is explicitly declared static is local to its translation unit. That name has internal linkage. This means that you can use the same name in other translation units without a name clash.
[update on Aug. 15, 08] was asked again about the 3 functionalities of 'static', such as global static function, global static variable... still choked...
[update on Nov. 30, 09 from]
Static has three distinct uses in C:
  • A variable declared static within the body of a function maintains its value between function invocations
  • A variable declared static within a module, (but outside the body of a function) is accessible by all functions within that module. It is not accessible by functions within any other module. That is, it is a localized global
  • Functions declared static within a module may only be called by other functions within that module. That is, the scope of the function is localized to the module within which it is declared

No comments:

Post a Comment