corrosion-rs / corrosion

Marrying Rust and CMake - Easy Rust and C/C++ Integration!
https://corrosion-rs.github.io/corrosion/
MIT License
1.02k stars 97 forks source link

Docs: C++ program linking stdlib statically #540

Closed Oipo closed 1 week ago

Oipo commented 1 week ago

I have a project that creates multiple cdylib using corrosion, but those resulting cdylibs are imported using dlopen instead of using CMake's target_link_libraries. As a result, when trying to dlopen the cdylib, the libstd-d5189b81a4fa4d36.so cannot be found. Because of having multiple cdylibs, statically linking stdlib to every cdylib is not preferable.

I couldn't find out what arguments to pass to the cmake executable definition to get it to statically link to the rust stdlib. Is there anything that corrosion provides at this time to facilitate this?

Thanks.

jschwe commented 1 week ago

but those resulting cdylibs are imported using dlopen instead of using CMake's target_link_libraries.

Are you sure that dlopening is the real cause for this issue?

As a result, when trying to dlopen the cdylib, the libstd-d5189b81a4fa4d36.so cannot be found.

Are you running the executable on the same machine that built the project? Does the libstd.so get found if you manually export the environment variable LD_LIBRARY_PATH=$HOME/.rustup/toolchains/<your_toolchain>/lib before running your executable? (please note that you need to replace <your_toolchain> with the full name of the Rust toolchain you built your project with - just look into the folder to see what options are there). If that works, then you'll probably want to set the rpath by passing -rpath=something to the linker - and if you are shipping your project to other machines, you would also need to package the stdlib .so.

Because of having multiple cdylibs, statically linking stdlib to every cdylib is not preferable.

I couldn't find out what arguments to pass to the cmake executable definition to get it to statically link to the rust stdlib. Is there anything that corrosion provides at this time to facilitate this?

These two statements conflict a bit, so I'm not quite sure what you want. I believe the standard behavior is to statically link the rust stdlib - you may want to check if you are somewhere setting the -C prefer-dynamic rustflag.

Oipo commented 1 week ago

Ack, I'm living in la la land again. My imagined approach is not going to work.

What I want to achieve is having smaller library output (hence the dynamically linking to stdlib) but I don't control the environments of where these libraries will be deployed. As the rust toolchain is not installed there, I'll have to supply libstd myself. Yet another problem is that some of the libraries are compiled with different versions of rust. So if I wanted to go down the dynamic linking path, I would have to supply a copy of libstd for each library.

Maybe static linking is the easiest after all.

Sorry for taking up your valuable time.