Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internal linkage with static keyword in C

Tags:

c

static

linkage

I know static is an overloaded keyword in C. Here, I'm only interested in its use as a keyword to enforce internal linkage.

If you have a global variable declared in a .c file, what is the difference between using static and not using static? Either way, no other .c file has access to the variable, so the variable is basically "private" to the file, with or without the static keyword.

For example, if I have a file foo.c, and I declare a global variable:

int x = 5;

That variable x is only available to code inside foo.c (unless of course I declare it in some shared header file with the extern keyword). But if I don't declare it in a header file, what would be the difference if I were to type:

static int x = 5.

Either way, it seems x has internal linkage here. So I'm confused as to the purpose of static in this regard.

like image 245
Channel72 Avatar asked Aug 19 '10 19:08

Channel72


People also ask

Which keyword is used for internal linkage?

To use internal linkage we have to use which keyword? Explanation: static keyword is used for internal linkage.

What is internal linkage in C?

Internal Linkage: An identifier implementing internal linkage is not accessible outside the translation unit it is declared in. Any identifier within the unit can access an identifier having internal linkage. It is implemented by the keyword static .

Can we use static and extern together in C?

Static variables in C have the following two properties: They cannot be accessed from any other file. Thus, prefixes “ extern ” and “ static ” cannot be used in the same declaration.

What kind of linkage do static class functions have?

The static keyword, when used in the global namespace, forces a symbol to have internal linkage. The extern keyword results in a symbol having external linkage.


1 Answers

If you have a global variable declared in a .c file, what is the difference between using static and not using static? Either way, no other .c file has access to the variable [...]

A different file could declare x:

extern int x;

That would allow code referencing x to compile, and the linker would then happily link those references to any x it finds.

static prevents this by preventing x from being visible outside of its translation unit.

like image 151
sbi Avatar answered Nov 05 '22 19:11

sbi