简体   繁体   English

全局静态函数仍在另一个文件中工作

[英]Global static function still working in another file

I declared a global static function in one file我在一个文件中声明了一个全局静态函数

ac交流电

static void Func1(void);
void Func2(void);

void Func1(void) {
    puts("Func1 Called");
}

void Func2(void) {
    puts("Func2 Called");
}

and accessed it in bc并在 bc 访问它

#include <stdio.h>
#include "a.c"
void main() {
    Func1();
    Func2();
}

the program complied successfully, but as per provided information this should give error: undefined reference to Func1 .程序成功编译,但根据提供的信息,这应该给出 error: undefined reference to Func1 What wrong is happening here?这里发生了什么错误?

You don't include a source file in another, you compile and link them together.您不将源文件包含在另一个文件中,而是将它们编译并链接在一起。

In you case, by saying #include "ac" , you're essentially putting the whole content of ac into bc and then starting the compilation, so the static functions and their calls are present in the same translation unit.在您的情况下,通过说#include "ac" ,您实际上是将ac的全部内容放入bc然后开始编译,因此static函数及其调用存在于同一个翻译单元中。 Thus, there is no issue for compiler to find the called function.因此,编译器没有问题可以找到被调用的函数。

Instead, if you do something like相反,如果你做类似的事情

gcc a.c b.c -o a.out //try to compile and link together

you'll see the expected error, as in this case, ac and bc will be two separate translation units.您会看到预期的错误,因为在这种情况下, acbc将是两个独立的翻译单元。

You declare in header files and define in .c files.您在header文件中声明并在.c文件中定义。 So you must use header files to represent the variables or functions you defined.所以你必须使用头文件来表示你定义的变量或函数。 Instead if you use .c files then it leads to multiple definitions.I think that is why you can access that global function.相反,如果您使用.c文件,则会导致多个定义。我认为这就是您可以访问该全局函数的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM