compiler-explorer icon indicating copy to clipboard operation
compiler-explorer copied to clipboard

Change crate-type when linking to bin

Open dkm opened this issue 1 year ago • 6 comments

When there is a fn main(), it would be better to use --crate-type bin instead of --crate-type lib. This would avoid having to make main explicitly public to stop the compiler from gc-ing it. That's what rust playground is doing (thanks @bjorn3 for the hint)

dkm avatar Mar 29 '23 16:03 dkm

Using --crate-type bin will pull in a lot of standard library code. -Cprefer-dynamic to dynamically link libstd may be an option, but that is incompatible with #![no_std] and #[global_allocator].

bjorn3 avatar Mar 29 '23 16:03 bjorn3

We have 3 use cases, for which we do the following:

  • compile (stop at assembly) => --crate-type rlib
  • compile to object (stop after assembling, ".o") => --crate-type lib
  • link to binary => --crate-type bin

Basically, the first case only emits assembly, the 2nd one before involving the linker, and the last one builds a running program.

I'm not familiar enough with rustc to really understand what the different crate types really do.

Can we use --crate-type bin for the first case for example?

Adding the link you gave elsewhere to rust playground code : https://github.com/rust-lang/rust-playground/blob/764833ed74d07e25bced2fedd4adb89dfeedebbe/ui/frontend/selectors/index.ts#L23

dkm avatar Mar 29 '23 18:03 dkm

If you use --emit asm instead of disassembling the linked output artifact (where linked in case of --crate-type lib means the .rlib file not the output of the linker), using --crate-type bin should be fine. Only the assembly for the current crate gets emitted by --emit asm.

bjorn3 avatar Mar 29 '23 19:03 bjorn3

Ok, thanks for the very precise answer (as always:)). We are using --emit asm, so I'll try to implement this little suggestion.

dkm avatar Mar 29 '23 19:03 dkm

@dkm is this something you're still working on? I'm a first-time contributor to the repo who'd like to dip his feet in, and this seems right up my alley! Let me know if I can work on this

ameya-deshmukh avatar Jun 04 '23 07:06 ameya-deshmukh

On June 4, 2023 7:32:40 AM UTC, Ameya Deshmukh @.***> wrote:

@dkm is this something you're still working on? I'm a first-time contributor to the repo who'd like to dip his feet in, and this seems right up my alley! Let me know if I can work on this

I'm not working on this. Can't remember the details, but I initially thought it would be very quick, but changed my mind after looking a bit more into it. Feel free to take over ! More than welcome! Don't hesitate to ask any question. I probably won't be able to answer, but other will !

dkm avatar Jun 04 '23 10:06 dkm