/* Ajith - Syntax Higlighter - End ----------------------------------------------- */


Static Functions in C

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.
#include "header.h"

int main()
return 0;
#include "header.h"

void hello()
printf("HELLO WORLD\n");
#include <stdio.h>

static void hello();
If we compile above code it fails as shown below
$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.

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...


  1. Very helpful for organizing software

  2. This code doesn't compile because "void int" isn't a valid return-type (@func.c+03).

    I don't think you've figured static functions out.

  3. Thanks for the find saul .. actually its just "void" ... I have updated the example.

  4. Short and useful :-) Thanks, I'm new to C.

  5. very useful.thanks

  6. Thanks for explanation.
    Can you please show me example how to compile this code (gcc main.c func.c) in Turbo C (installed on Windows OS) and OpenVMS?

    I have tried in Turbo C but unable to get how code with 2 c files at a time can be compiled.


  7. Hi, Sandeep

    you can compile 2 c file by include one of them in other like if you have two files file1.c and file2.c the in file1.c you can include it as

    #include "file2.c"


Your comments are moderated