Static functions in C

4

I noticed that some libraries use functions and static variables, such as static int sum(lua_State *state) .

This function belongs to a library that will be compiled into the Lua language.

But also libraries with dlsym calls also have static functions.

What does the use of static functions in libraries provide differently with non-static functions?

    
asked by anonymous 14.12.2016 / 05:37

1 answer

5

C has no methods, only functions (the original question spoke in methods). Although C ++ has methods, if only the functions are static. What is known by static method in Java and C #, for example is just a function in these languages.

In C the static in fact is a form similar to private . Since there are no classes, this applies to the file in which it was declared, so it can only be called there in that file.

Static variables mean that they have a global state. When a variable is declared with static , it is not placed in either the stack or heap , but in a static area, so it is already reserved by the compiler in the executable. The lifetime , of course, is for the duration of the application. This is considered global status and can cause problems if the application has concurrent access, or even if you do not take certain care.

There are two possible visibilities when the variable is static. If it is inside the function, it will only be visible there. Every time you call the function this variable will have the last value it had on the last call, it is not destroyed at the end of its execution.

If it is outside the function, it will only be visible in the file, just like the function.

In C it is rare to use static variables. Functions are very useful for decreasing visibility. In C ++ it is recommended to avoid both since it has better mechanism.

There is no special use for libraries. In fact it is the opposite, as it makes it private, whoever consumes the library will never access it under normal conditions. The most you can say is that it prevents access, but this is not exclusive to libraries.

Example:

#include <stdio.h>

static int externa = 1;

static void teste() {
    int x = 0;
    static int estatica = 0;
    x++;
    estatica++;
    printf("x = %d, estatica = %d, externa = %d\n", x, estatica, externa);
}
int main() {
    printf("externa = %d\n", externa);
    for (int i = 0; i < 10; i++) {
        teste();
    }
}

See working on ideone and on CodingGround .

Try to create another file, and call the teste() function or the externa variable. Will not compile. Obviously you would need a header . If you include this file, then it will be part of the other file and compile.

    
14.12.2016 / 11:56