Why do you use the static function of C?

Asked 2 years ago, Updated 2 years ago, 96 views

Question about the C static function says there's a static function I wonder why you make a function only available in the same file.

c static

2022-09-22 22:19

1 Answers

Since the static function is only visible within the same translation unit, Write when you don't want other translation units to know the existence of this function (encapsulation)

helper_file.c:

int f1(int);        /* prototype */
static int f2(int); /* prototype */

int f1(int foo) {
    return f2(foo); /* f1 and f2 are possible because they are in the same translation unit */
}

int f2(int foo) {
    return 42 + foo;
}

main.c:

int f1(int); /* prototype */
int f2(int); /* prototype */

int main(void) {
    f1(10); /* f1 is seen on the linker - ok */
    f2(12); /* f2 is not visible to linker - error */
    return 0;
}


2022-09-22 22:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.