简体   繁体   English

未使用的变量和函数的链接器错误

[英]Linker error of unused variable and function

I have written following test program我编写了以下测试程序

int proc1();
extern int globalvar;

int func1 ()
{
    return globalvar + 1;
}

int func2()
{
    return proc1()+3;
}

int main()
{
    return 0;
}

As you can see that this program is not doing anything.正如你所看到的,这个程序没有做任何事情。 However, while compiling it, I faced linker error of globalvar and int proc1() despite the facts that these are not going to be referenced from the entry point function main .然而,在编译它时,我遇到了globalvarint proc1()链接器错误,尽管它们不会被入口点函数main引用。 I faced problem on both Windows(using cl ) and Linux(using gcc ).我在 Windows(使用cl )和 Linux(使用gcc )上都遇到了问题。

Is there any way to instruct the compiler/linker not to link this unreferenced global variable and function from the entry point (on cl, gcc and clang)?有什么方法可以指示编译器/链接器不要从入口点(在 cl、gcc 和 clang 上)链接这个未引用的全局变量和函数?

Exact error message on Windows: Windows 上的确切错误消息:

test.obj : error LNK2019: unresolved external symbol "int globalvar" (?globalvar@@3HA) referenced in function "int __cdecl func1(void)" (?func1@@YAHXZ)
test.obj : error LNK2019: unresolved external symbol "int __cdecl proc1(void)" (?proc1@@YAHXZ) referenced in function "int __cdecl func2(void)" (?func2@@YAHXZ)
test.exe : fatal error LNK1120: 2 unresolved externals

You can fix this, in gcc , like this:您可以在gcc修复此问题,如下所示:

gcc -ffunction-sections -Wl,--gc-sections test.c

That does two things:这有两件事:

  1. It instructs the compiler to emit each function in its own 'section' in the binary file.它指示编译器在二进制文件中自己的“部分”中发出每个函数。

  2. It instructs the linker to discard (garbage collect) sections that are not referenced.它指示链接器丢弃(垃圾收集)未引用的部分。

This means that func1 and func2 will be discarded, and therefore there will be not more references to globalvar or proc1 .这意味着func1func2将被丢弃,因此不会有更多对globalvarproc1引用。

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

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