[英]Does static function hide non-static function with the same name?
I tried to look this up, but did not find it anywhere. 我试图查找它,但没有在任何地方找到它。 So here's the question:
所以这是一个问题:
Static functions in C/C++ can be used to "make them invisible to the outer world". C / C ++中的静态函数可用于“使它们对于外部世界不可见”。 Great, when having two same-named static functions in two different compiled units (.c files), it makes me sure that I call the right one.
太好了,当在两个不同的编译单元(.c文件)中具有两个同名的静态函数时,可以确保我调用正确的静态函数。 But can I also be sure that I call my local static function when there exists a same-named non-static function somewhere in the project or libraries?
但是,如果在项目或库中某处存在同名的非静态函数,是否还可以确保我调用本地静态函数? That is, does the static function locally hide the non-static one?
也就是说,静态函数是否在本地隐藏了非静态函数?
Sure I can test it (and I did) but I want to know whether this behaviour has fixed definition in C/C++. 当然可以测试(并且确实可以),但是我想知道这种行为在C / C ++中是否具有固定的定义。 Thanks.
谢谢。
Edit : Simplified example code which caused unexpected behaviour to me. 编辑 :简化的示例代码,这对我造成了意外的行为。 The question is about the fix of the problem (suppose I cannot change the library).
问题是解决该问题 (假设我无法更改库)。
In mylib.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));
}
In mylib.h: 在mylib.h中:
// only libfunc is declared here
void libfunc(void);
In myprog.c: 在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));
}
Compiled mylib.c
+ further files
-> mylib.a
编译了
mylib.c
+ further files
-> mylib.a
Compiled myprog.c
-> myprog.o
编译
myprog.c
> myprog.o
Linked myprog.o
+ mylib.a
-> myprog
链接
myprog.o
+ mylib.a
> myprog
You'd get a compilation error because functions have default external linkage, thus the new static
function would result in a conflict of linkage specifiers. 由于函数具有默认的外部链接,因此会出现编译错误,因此新的
static
函数将导致链接说明符冲突。
If the declaration of the non- static
function isn't visible, the static
one will be called: 如果不声明
static
函数是不可见的,在static
一个将被调用:
void foo(); //external linkage
static void foo() {}; //internal linkage and error
It does not hide functions with same name declared in the same scope. 它不会隐藏在相同作用域中声明的具有相同名称的函数。 However you may not have a function with the same signature declared as having internal and external linkage.
但是,您可能没有具有声明为具有内部和外部链接的相同签名的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.