gpt4 book ai didi

c - 是声明一个静态函数以使其私有(private)化还是仅在 .c 文件中声明它并将其从 header 中排除更好?

转载 作者:太空宇宙 更新时间:2023-11-04 06:11:09 25 4
gpt4 key购买 nike

我正在用 c 编写一个库,有些函数我希望可以从其他 c 文件调用,有些我想保持私有(private)。

我知道可以通过将函数声明为 static 来隐藏库文件之外的函数,但同样可以通过仅声明其实现并将其从 header 中删除来实现。

比较:

a.h

//static int private_routine();
int sample();


a.c

/*static*/ int private_routine(){

}
int sample(){
private_routine();
}

哪种做法最好?

最佳答案

要在单个文件的范围内保持函数“私有(private)”或更好,您需要将它们声明为static。否则,您可以在其他文件中重新声明相同的函数并继续使用它。

例如:

#include "a.h" // without declaration of private_routine()

/*extern*/ int private_routine(); // by default every declaration behaves as with extern keyword, which means function is defined elsewhere

int main()
{
private_routine(); // can use here
return 0;
}

编辑:正如评论中所指出的,如果不将其声明为static,则不可能在一个应用程序中多次定义具有相同名称的函数。如果您定义一个给定的函数名称 N 次,其中至少有 N-1 次必须是 static

关于c - 是声明一个静态函数以使其私有(private)化还是仅在 .c 文件中声明它并将其从 header 中排除更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56427972/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com