簡體   English   中英

未使用的變量和函數的鏈接器錯誤

[英]Linker error of unused variable and function

我編寫了以下測試程序

int proc1();
extern int globalvar;

int func1 ()
{
    return globalvar + 1;
}

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

int main()
{
    return 0;
}

正如你所看到的,這個程序沒有做任何事情。 然而,在編譯它時,我遇到了globalvarint proc1()鏈接器錯誤,盡管它們不會被入口點函數main引用。 我在 Windows(使用cl )和 Linux(使用gcc )上都遇到了問題。

有什么方法可以指示編譯器/鏈接器不要從入口點(在 cl、gcc 和 clang 上)鏈接這個未引用的全局變量和函數?

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

您可以在gcc修復此問題,如下所示:

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

這有兩件事:

  1. 它指示編譯器在二進制文件中自己的“部分”中發出每個函數。

  2. 它指示鏈接器丟棄(垃圾收集)未引用的部分。

這意味着func1func2將被丟棄,因此不會有更多對globalvarproc1引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM