Search code examples
c++cunixgccstatic

Static function access in other files


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


Solution

  • 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 can 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