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"func.c
int main()
{
hello();
return 0;
}
#include "header.h"header.h
void hello()
{
printf("HELLO WORLD\n");
}
#include <stdio.h>If we compile above code it fails as shown below
static void hello();
$gcc main.c func.cIt 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.
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
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...
very useful
ReplyDeleteVery helpful for organizing software
ReplyDeleteThis code doesn't compile because "void int" isn't a valid return-type (@func.c+03).
ReplyDeleteI don't think you've figured static functions out.
Booga booga
DeleteThanks for the find saul .. actually its just "void" ... I have updated the example.
ReplyDeleteShort and useful :-) Thanks, I'm new to C.
ReplyDeletevery useful.thanks
ReplyDeleteThanks for explanation.
ReplyDeleteCan 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.
Thanks
Hi, Sandeep
ReplyDeleteyou 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"