This blog is under construction

Tuesday, 31 December 2013

Static function in c

What is static function in C?
Static function is nothing but a function that is callable only by other functions in the same file where the static function is defined.

Static function example:
Consider the following example,
 
  // static.c is the file name
  static int add(int a, int b) {
        return (a + b);
  }

Here, we have defined a static function named add() in static.c.  Below is main.c file which has main function calling another function named add().

 
  // main.c
  #include <stdio.h>
  int main() {
        int res;
        res = add(10, 20);  // main function makes call to static function
        printf("Result: %d\n", res);
        return 0;
  }


Let us try to compile both together to get a single executable.
  Output:
  jp@jp-VirtualBox:~/$ gcc static.c main.c 
  /tmp/ccSWRV5a.o: In function `main':
  ex45.c:(.text+0x19): undefined reference to `add'
  collect2: ld returned 1 exit status


From main function, we are calling a static function named add() in another another file. This results to the above error. Basically, static functions are not allowed to be called from other files. 

Let us see what happens if we make static function as non-static.
 
  // static.c is the file name
  int add(int a, int b) {
        return (a + b);
  }

 
  // main.c
  #include <stdio.h>
  int main() {
        int res;
        res = add(10, 20);  // main function makes call to static function
        printf("Result: %d\n", res);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ gcc static.c main.c 
  jp@jp-VirtualBox:~/$ ./a.out
  Result: 30



No comments:

Post a Comment