Hairi
Hairi

Reputation: 3715

Static function is visible for another file

I am trying to understand how static functions work. I read that the static function can not be called from another file so I made a simple function in a file and than called it from another fail to see if it is callable. It is, but it shouldnt be. Here is my first file: riko_driver which contains the function:

static void sfunc(void)
{
   puts("Static function has been called\n");
}

And this is my code (main.c) which calls the function from riko_driver.c

#include <stdio.h>
#include <stdlib.h>
#include <riko_driver.c>

int main(){
sfunc();
system("PAUSE");    
return 0;
}

As an output I got this: "Static function has been called" But I shouldn't wright? Because I can not call static function from another file? I hope you understand my question. Excuse my bad English!

Upvotes: 2

Views: 1323

Answers (2)

R Sahu
R Sahu

Reputation: 206567

You said:

I read that the static function can not be called from another file

That is almost correct. It should be:

A static function defined in one translation unit can not be called from another translation unit.

By adding

#include <riko_driver.c>

in main.c, you are making the contents of riko_driver.c part of the translation unit main.c.

If you want the static functions defined in riko_driver.c to be not usable from main.c but you want some extern funtions defined in riko_driver.c to be usable from main.c,

  1. Create a header file, riko_driver.h, that contains the declarations of the extern functions.
  2. Use #include "riko_driver.h" in main.c instead of #include <riko_driver.c>.
  3. Use #include "riko_driver.h" in riko_driver.c so that the compiler checks consistency.
  4. Compile main.c and riko_driver.c separately.
  5. Link main.o and riko_driver.o to make the executable.

Upvotes: 4

ouah
ouah

Reputation: 145829

To say that a static function can only be called in the file it has been defined is actually a shortcut to the fact that a static function only has visibility in the translation unit it has been defined. In C terminology we say that the identifier for the function has internal linkage.

If you include a file into another file and compile the source file you still have a single translation unit.

Upvotes: 4

Related Questions