Adding link libraries at build time

Hi,

I’m currently maintaining Corrosion which integrates Rusts cargo build system into CMake.
When linking Rust static libraries into C/C++ code (managed by CMake), we also need to link some system libraries (e.g. pthread). Currently, the required libraries are hardcoded in corrosion, based on what is usually required for the target OS. Ideally though, we would like to ask rustc which libraries we need to link. rustc provides an option --print native-static-libs which prints a list of required libraries.

This list is produced during the actual build of the static library. Using a dummy demo project to get a list of libraries is also not sufficient in all cases, since rustc will actually take all dependencies into consideration and any #[link] attributes in the source code, which may specify libraries to link against. Build-scripts may also add additional libraries to the list of libraries that should be linked.

Is there any way that we could respect this list of required libraries, generated at build-time, and add them to the target CMake C/C++ executable via target_link_libraries()? From my understanding currently there is no way to do this in CMake, unless we would prebuild the Rust project at configure time.

One way you could do this is to add a link option of @rspfile. You probably want to do this as an INTERFACE on the Rust target and write it via some POST_LINK custom command on that target. Or add it to the custom command chain if it is already a chain of custom commands.

Note that because of the build-time discovery, libraries will be duplicated on the command line because sorting and filtering the link line requires generator-time knowledge which has been thrown away by then.

One way you could do this is to add a link option of @rspfile

Thanks, that sounds useful! Is this @rspfile a Windows / MSVC specific linker option? I looked at the documentation for ld and couldn’t find anything which would allow me to load arguments from a file.

CMake uses the compiler frontend, so you actually want gcc and/or clang docs and they support response files. ar supports response files though according to its manpage.