Thursday, August 28, 2014

static functions

static functions


Nature of C fucntions:

By default C function are global (i.e. extern)

purpose of static fucntions:
  • to restrict the function access with in the file
  • To reuse the function name in the multiple file
Example1:

root@selvakumar-Lenovo-B460e:/C_pgms/static# cat one.c two.c 
static void fun()
{
printf("\nfun\n");
}

#include<stdio.h>
int main()
{
fun();
return 0;
}

root@selvakumar-Lenovo-B460e:/C_pgms/static# gcc one.c two.c 
/tmp/ccube8pe.o: In function `main':
two.c:(.text+0x7): undefined reference to `fun'
collect2: ld returned 1 exit status
root@selvakumar-Lenovo-B460e:/C_pgms/static# 

When non static:

root@selvakumar-Lenovo-B460e:/C_pgms/static# cat one.c two.c 
void fun()
{
printf("\nfun\n");
}

#include<stdio.h>
int main()
{
fun();
return 0;
}
root@selvakumar-Lenovo-B460e:/C_pgms/static# gcc one.c two.c 
root@selvakumar-Lenovo-B460e:/C_pgms/static# ./a.out 

fun
root@selvakumar-Lenovo-B460e:/C_pgms/static# 


Example2:


without static:


root@selvakumar-Lenovo-B460e:/C_pgms/static-func# cat three.c four.c
void fun()
{
printf("\nfun\n");
}

#include<stdio.h>
void fun()
{
printf("\nfun\n");
}
int main()
{
fun();
return 0;
}
root@selvakumar-Lenovo-B460e:/C_pgms/static-func# gcc three.c four.c
/tmp/cc6EUER9.o: In function `fun':
four.c:(.text+0x0): multiple definition of `fun'
/tmp/cca8Agtk.o:three.c:(.text+0x0): first defined here
collect2: ld returned 1 exit status
root@selvakumar-Lenovo-B460e:/C_pgms/static-func#

with static:

root@selvakumar-Lenovo-B460e:/C_pgms/static-func# cat three.c four.c 
static void fun()
{
printf("\nfun\n");
}
#include<stdio.h>
void fun()
{
printf("\nfun\n");
}
int main()
{
fun();
return 0;
}
root@selvakumar-Lenovo-B460e:/C_pgms/static-func# gcc three.c four.c 
root@selvakumar-Lenovo-B460e:/C_pgms/static-func# ./a.out 

fun
root@selvakumar-Lenovo-B460e:/C_pgms/static-func# 


No comments:

Post a Comment