Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static function in c

Tags:

c

static

I thought that a function in C which is declared static is only visible in the file were i defined it. In the following example the static var is visible in another file. im not quite sure if it is because of the include:

main.c:

#include "test.c"

int main() {
    test();
}

test.c:

static void test() {
    // do something here
}

void foo() {
   // do something different here
}

if it's only working with a header file isn't it totally useless then? If i want to hide a function then i don't mention it in the header file?!

like image 783
fliX Avatar asked Jul 06 '26 00:07

fliX


1 Answers

#include is a preprocessor directive. When the preprocessor (that runs before compiling) sees it, it will copy the contents of the included file over there. So you end up with it in the same file.

if its only working with a header file isnt it totaly useless then? if i want to hide a function then i dont mention it in the header file?!

Sure, but not mentioning it in the header file won't "hide" it. The header file is not compiled, if you place your prototypes there it acs as a clue to the compiler.

The advantage of static functions is that they won't be visible outside the file —in the sense that it won't be global in your object file. This allows you to use in other files the same symbol (name) for another thing, without a conflict.

like image 181
sidyll Avatar answered Jul 08 '26 14:07

sidyll