静态函数是否隐藏具有相同名称的非静态函数

Does static function hide non-static function with the same name?

本文关键字:静态函数 是否 隐藏      更新时间:2023-10-16

我试着查找它,但在任何地方都找不到。所以问题来了:

C/C++中的静态函数可以用来"使它们对外部世界不可见"。很好,当在两个不同的编译单元(.c文件)中有两个相同名称的静态函数时,它可以确保我调用了正确的静态函数但是,当项目或库中的某个位置存在相同名称的非静态函数时,我是否也可以确保调用本地静态函数也就是说,静态函数是否在本地隐藏非静态函数?

当然我可以测试它(我确实测试过),但我想知道这种行为在C/C++中是否有固定的定义。谢谢

编辑:简化的示例代码导致了我的意外行为。问题是关于问题的解决(假设我无法更改库)。

在mylib.c中:

#include "mylib.h"
int send(void * data, int size);
...
int send(void * data, int size) {
return send_message(queueA, data, size);
}
void libfunc(void) {
send(str, strlen(str));
}

在mylib.h中:

// only libfunc is declared here
void libfunc(void);

在myprog.c:中

#include "mylib.h"
int send(void * data, int size);
...
int send(void * data, int size) {
return send_message(queueB, data, size);
}
void progfunc(void) {
// expected to send a message to queueB
// !!! but it was sent to queueA instead !!!
send(str, strlen(str));
}

编译mylib.c+further files->mylib.a

编译myprog.c->myprog.o

链接myprog.o+mylib.a->myprog

您会得到一个编译错误,因为函数具有默认的外部链接,因此新的static函数将导致链接说明符的冲突。

如果非static函数的声明不可见,则会调用static函数:

void foo();            //external linkage
static void foo() {};  //internal linkage and error

它不隐藏在同一范围内声明的同名函数。但是,您可能没有将具有相同签名的函数声明为具有内部和外部链接。

相关文章: