静态函数的外部声明是否会破坏内部链接?
我有一个理论问题。
下面是一个例子:
file1.c
static void foo()
{
...
}
file2.c
extern void foo();
main()
{
foo();
}
编译正常。
那么,extern 破坏了静态声明的内部链接吗?
I have a theoretical question.
Here's an example:
file1.c
static void foo()
{
...
}
file2.c
extern void foo();
main()
{
foo();
}
The compilation is OK.
So, the extern breaks the internal linkage of static declaration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
“编译没问题”只是理论上的,还是你实际测试过的?
static
函数从其所在的编译单元(通常是 C 文件)外部不应该是可见的。在不同的编译单元中使用
extern
声明同名的函数不应该改变这一点。确保您确实正确地构建并链接测试程序,否则您要测试的只是可以对外部符号(
foo
2.c) 中引用的函数。将 2.c 构建到可执行文件(即链接它)应该会失败。Is the "compilation ok" only in theory, or did you actually test this?
A
static
function should not be visible from outside the compilation unit (C file, typically) that it's in.Declaring a function of the same name with
extern
in a different compilation unit should not change this.Make sure you really build and link the test program properly, since otherwise all that you're testing is that you can have a "dangling" reference to an external symbol (the
foo
function referenced from 2.c). Building 2.c into an executable (i.e. linking it) should fail.编译应该没问题。如果您也可以链接它,则您的编译器有问题。
The compilation should be OK. If you can also link that, your compiler have a problem.
快速测试确认了预期的链接器失败(VC++ 2010 Express):
1>test.obj:错误LNK2019:函数_wmain中引用的无法解析的外部符号“void __cdecl foo(void)”(?foo@@YAXXZ)
A quick test confirms the expected linker failure (VC++ 2010 express):
1>test.obj : error LNK2019: unresolved external symbol "void __cdecl foo(void)" (?foo@@YAXXZ) referenced in function _wmain