静态函数是否隐藏具有相同名称的非静态函数
Does static function hide non-static function with the same name?
我试着查找它,但在任何地方都找不到。所以问题来了:
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
它不隐藏在同一范围内声明的同名函数。但是,您可能没有将具有相同签名的函数声明为具有内部和外部链接。
相关文章:
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 在 nullptr 上调用无状态类的非静态成员函数是否合法?
- 检查编译时是否存在静态函数
- 内联函数的函数本地静态对象是否在共享对象文件之间共享?
- 如果 C 函数仍然可以间接执行(通过回调函数),那么将它声明为静态函数是否是一种不好的做法?
- 使用静态成员函数而不是普通函数是否有任何开销?
- 在C 中,静态成员函数是否继承了?如果是,为什么没有出现歧义错误
- GCC 警告未使用的静态函数,但不警告静态内联:是否有实际区别?
- 如果基类是公开继承的,那么基类的公共静态函数是否会成为派生类的成员函数
- 静态函数是否隐藏具有相同名称的非静态函数
- 静态断言以检查构造函数是否显式
- 一个定义规则是否强制创建一个静态函数变量
- 在对象是静态的类函数中声明静态变量是否有意义
- cpp 正文线程的本地函数是否安全?如果是这样,从中调用静态函数呢?
- 引用静态函数作为类定义的一部分是否有任何开销?
- 非静态成员函数是否可以具有与其内部定义的类相同的类型?
- 非静态成员函数是否可以访问静态成员函数或数据
- 函数局部静态变量是否阻止函数内联?
- 函数局部静态变量是否自动引发分支?
- C++中是否有"static class",例如要在同一文件中访问的静态函数?