douwen1549 2018-02-08 15:16 采纳率: 100%
浏览 43
已采纳

将使编译器忽略未使用的功能

If there is a function from an external package that is not used at all in my project, will the compiler remove the function from the generated machine code?

This question could be targeted at any language compiler in general. But, I think the behaviour may vary language to language. So, I am interested in knowing what does go compilers do.

I would appreciate any help on understanding this.

  • 写回答

1条回答 默认 最新

  • douhuang7263 2018-02-08 15:20
    关注

    The language spec does not mention this anywhere, and from a correctness point of view this is irrelevant.

    But know that the current version does remove certain constructs that the compiler can prove is not used and will not change the runtime behaviour of the app.

    Quoting from The Go Blog: Smaller Go 1.7 binaries:

    The second change is method pruning. Until 1.6, all methods on all used types were kept, even if some of the methods were never called. This is because they might be called through an interface, or called dynamically using the reflect package. Now the compiler discards any unexported methods that do not match an interface. Similarly the linker can discard other exported methods, those that are only accessible through reflection, if the corresponding reflection features are not used anywhere in the program. That change shrinks binaries by 5–20%.

    Methods are a "harder" case than functions because methods can be listed and called with reflection (unlike functions), but the Go tools do what they can even to remove unused methods too.

    You can see examples and proof of removed / unlinked code in this answer:

    How to remove unused code at compile time?

    Also see other relevant questions:

    Splitting client/server code

    Call all functions with special prefix or suffix in Golang

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向