Game Mechanics is an Indie company based in India ,founded by two college students when making their first ever game just for learning purpose. We aim to make unique gameplay mechanics with creative content.

Post tutorial Report RSS Using Static

How Static keyword can be used in different ways in different contexts

Posted by on - Intermediate Client Side Coding

By default all functions are implicitly declared as extern, which means they're visible across translation units. But when we use static it restricts visibility of the function to the translation unit in which it's defined. So we can say
Functions that are visible only to other functions in the same file are known as static functions.

Let use try out some code about static functions.

main.c

#include "header.h"

int main()
{
hello();
return 0;
}

func.c

#include "header.h"

void int hello()
{
printf("HELLO WORLD\n");
}

header.h
view plainprint?
#include

static int hello(); If we compile above code it fails as shown below
view plainprint?
$gcc main.c func.c
header.h:4: warning: "hello" used but never defined
/tmp/ccaHx5Ic.o: In function `main':
main.c:(.text+0x12): undefined reference to `hello'
collect2: ld returned 1 exit status
It fails in Linking since function hello() is declared as static and its definition is accessible only within func.c file but not for main.c file. All the functions within func.c can access hello() function but not by functions outside func.c file.

Using this concept we can restrict others from accessing the internal functions which we want to hide from outside world. Now we don't need to create private header files for internal functions.

Note:
For some reason, static has different meanings in in different contexts.

1. When specified on a function declaration, it makes the function local to the file.
2. When specified with a variable inside a function, it allows the variable to retain its value between calls to the function. See static variables.

It seems a little strange that the same keyword has such different meanings...

Post a comment

Your comment will be anonymous unless you join the community. Or sign in with your social account: