Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static function access in other files

Tags:

c++

c

unix

static

gcc

Is there any chance that a function defined with static can be accessed outside the file scope?

like image 405
Arpit Avatar asked Feb 02 '10 08:02

Arpit


People also ask

Can we access static function in another file?

Functions in C are global by default. To make them local to the file they are created, we use the keyword static before the function. Static functions can't be called from any other file except the file in which it is created. Using static function, we can reuse the same function name in different files.

What can a static function access?

A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared. Suppose a static member function f() is a member of class X . The static member function f() cannot access the nonstatic members X or the nonstatic members of a base class of X .

Which function can have access to only other static member?

Static method overloaded and static method can access only static members.

Can static function be public?

To call a static method from a child class, use the parent keyword inside the child class. Here, the static method can be public or protected .


1 Answers

It depends upon what you mean by "access". Of course, the function cannot be called by name in any other file since it's static in a different file, but you have have a function pointer to it.

$ cat f1.c
/* static */
static int number(void)
{
    return 42;
}

/* "global" pointer */
int (*pf)(void);

void initialize(void)
{
    pf = number;
}
$ cat f2.c
#include <stdio.h>

extern int (*pf)(void);
extern void initialize(void);

int main(void)
{
    initialize();
    printf("%d\n", pf());
    return 0;
}
$ gcc -ansi -pedantic -W -Wall f1.c f2.c
$ ./a.out
42
like image 95
Alok Singhal Avatar answered Oct 29 '22 21:10

Alok Singhal