本文介绍了为什么 Godbolt 编译器资源管理器在发布模式下编译时不显示我的函数的任何输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 https://rust.godbolt.org 查看这个函数的汇编输出:

I want to use https://rust.godbolt.org to see the assembly output of this function:

fn add(a: u8, b: u8) -> u8 {
    a + b
}

将其粘贴到网站上可以正常工作,但会显示大量程序集.这并不奇怪,因为 rustc 默认在调试模式下编译我的代码.当我在发布模式下编译 通过将 -O 传递给编译器,有根本没有输出!

Pasting this on the website works fine, but shows a lot of assembly. This is not unsurprising, given that rustc compiles my code in debug mode by default. When I compile in release mode by passing -O to the compiler, there is no output at all!

我做错了什么?为什么 Rust 编译器会在发布模式下删除所有内容?

What am I doing wrong? Why does the Rust compiler remove everything in release mode?

推荐答案

Godbolt 通过将 --crate-type=lib 传递给编译器,将您的 Rust 代码编译为库包.库中的代码只有在公开时才有用.因此,在您的情况下,您的 add() 函数是私有的,并且已从编译器中完全删除.解决方法很简单:

Godbolt compiles your Rust code as a library crate by passing --crate-type=lib to the compiler. And code from a library is only useful if it's public. So in your case, your add() function is private and is removed from the compiler completely. The solution is rather simple:

通过向函数添加 pub 来公开您的函数. 现在编译器不会删除该函数,因为它是您的库的公共接口的一部分.

Make your function public by adding pub to it. Now the compiler won't remove the function, since it is part of the public interface of your library.

这篇关于为什么 Godbolt 编译器资源管理器在发布模式下编译时不显示我的函数的任何输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 21:07