[英]Static function is visible for another file
I am trying to understand how static functions work. 我试图了解静态函数的工作原理。 I read that the static function can not be called from another file so I made a simple function in a file and than called it from another fail to see if it is callable.
我读到静态函数不能从另一个文件中调用,所以我在一个文件中创建了一个简单的函数,而不是从另一个文件调用它,看不到它是否可调用。 It is, but it shouldnt be.
它是,但它不应该。 Here is my first file: riko_driver which contains the function:
这是我的第一个文件:riko_driver,其中包含以下功能:
static void sfunc(void)
{
puts("Static function has been called\n");
}
And this is my code (main.c) which calls the function from riko_driver.c 这是我的代码(main.c),它从riko_driver.c调用该函数
#include <stdio.h>
#include <stdlib.h>
#include <riko_driver.c>
int main(){
sfunc();
system("PAUSE");
return 0;
}
As an output I got this: "Static function has been called" But I shouldn't wright? 作为输出我得到了这个:“静态功能被称为”但我不应该怀疑? Because I can not call static function from another file?
因为我不能从另一个文件中调用静态函数? I hope you understand my question.
我希望你理解我的问题。 Excuse my bad English!
请原谅我糟糕的英语!
You said: 你说:
I read that the static function can not be called from another file
我读到静态函数不能从另一个文件调用
That is almost correct. 这几乎是正确的。 It should be:
它应该是:
A static function defined in one translation unit can not be called from another translation unit.
不能从另一个翻译单元调用在一个翻译单元中定义的静态函数。
By adding 通过增加
#include <riko_driver.c>
in main.c
, you are making the contents of riko_driver.c
part of the translation unit main.c
. 在
main.c
,您正在将riko_driver.c
的内容作为翻译单元main.c
。
If you want the static
functions defined in riko_driver.c
to be not usable from main.c
but you want some extern
funtions defined in riko_driver.c
to be usable from main.c
, 如果你想让
riko_driver.c
定义的static
函数不能从main.c
使用,但你想在riko_driver.c
定义的一些extern
函数可以从main.c
,
riko_driver.h
, that contains the declarations of the extern
functions. riko_driver.h
,它包含extern
函数的声明。 #include "riko_driver.h"
in main.c
instead of #include <riko_driver.c>
. main.c
使用#include "riko_driver.h"
而不是#include <riko_driver.c>
。 #include "riko_driver.h"
in riko_driver.c
so that the compiler checks consistency. riko_driver.c
使用#include "riko_driver.h"
,以便编译器检查一致性。 main.c
and riko_driver.c
separately. main.c
和riko_driver.c
。 main.o
and riko_driver.o
to make the executable. main.o
和riko_driver.o
以生成可执行文件。 To say that a static function can only be called in the file it has been defined is actually a shortcut to the fact that a static function only has visibility in the translation unit it has been defined. 要说静态函数只能在它定义的文件中调用,实际上是静态函数只在已经定义的翻译单元中具有可见性这一事实的快捷方式。 In C terminology we say that the identifier for the function has internal linkage .
在C术语中,我们说该函数的标识符具有内部链接 。
If you include a file into another file and compile the source file you still have a single translation unit. 如果将文件包含到另一个文件中并编译源文件,则仍然只有一个翻译单元。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.