C中静态函数的用途 [英] Purpose of static function in C

查看:115
本文介绍了C中静态函数的用途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道静态函数的名字只在其声明的文件(翻译单元)内可见。这使得封装成为可能。

但是静态函数通常在源文件中声明,因为如果你在头文件中执行它,你可以最终实现它的多个实现我认为这不是静态)的意图。



示例:



main.c

  #include functions.h

int main()
{
FunctionA();
FunctionB(); //不管静态都无法调用。
返回0;
}

functions.h

  #ifndef FUNCTIONS_H 
#define FUNCTIONS_H

void FunctionA();

#endif / * FUNCTIONS_H * /

functions.c

  #includefunctions.h
#include < stdio.h中>

static void FunctionB(); //使用静态还是不使用。

void FunctionA()
{
printf(A);
}

void FunctionB()
{
printf(B);

所以当 static 有用吗?

解决方案

static 这意味着它不会与其他文件(翻译单元)中相同标识符的其他用途相链接。

例如,假设在 Tree中。 c 我有一个在Tree结构上运行的函数,我有一些本地子例程叫做 UpdateNode ,它在Tree的一部分上运行。进一步假设在 List.c 中,我有一个在List结构上运行的函数,它也有一些本地的子程序,叫做 UpdateNode 这只是列表结构,而不是Tree结构。



如果我将这两个子例程都用外部链接,链接器会抱怨多个定义。通过用 static 的内部链接标记它们,避免了这个问题。


I know that static function's name is visible only within the file (translation unit) in which it's declared. This makes encapsulation possible.

But static function is usually declared in the source file because if you do it in the header file, you can end up with multiple implementations of it (which I think is not the intention of static).

Example:

main.c

#include "functions.h"

int main()
{
    FunctionA();
    FunctionB(); // Can't call regardless of "static".
    return 0;
}

functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

void FunctionA();

#endif /* FUNCTIONS_H */

functions.c

#include "functions.h"
#include <stdio.h>

static void FunctionB(); // Same whether "static" is used or not.

void FunctionA()
{
    printf("A");
}

void FunctionB()
{
    printf("B");
}

So when is static useful?

解决方案

static says the function has internal linkage. This means it will not be linked with other uses of the same identifier in other files (translation units).

For example, suppose in Tree.c I have a function that operates on Tree structures, and I have some local subroutine called UpdateNode that operates on part of the Tree. Further suppose that in List.c, I have a function that operates on List structures, and it also has some local subroutine called UpdateNode that is just for List structures, not for Tree structures.

If I left both of these subroutines with external linkage, the linker would complain about multiple definitions. By marking them with internal linkage with static, this problem is avoided.

这篇关于C中静态函数的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆