How to link .o files generated by rustc?

So I saw the rustc compiler has the option to generate .o files, by specifying --emit obj. I tried using CMake to do the following..

add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Test.rs.o COMMAND rustc -o ${CMAKE_CURRENT_BINARY_DIR}/Test.rs.o --crate-type staticlib --emit obj ${CMAKE_CURRENT_SOURCE_DIR}/Source/Test.rs)
add_custom_target(Test.rs.o DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/Test.rs.o)

add_executable(CTest Source/Test.c)
target_link_libraries(CTest PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/Test.rs.o)
add_dependencies(CTest Test.rs.o)

This works but only without any use in the Test.rs file. As soon as I add for example use std::ffi::CString; a whole bunch of undefined reference errors are output by ld (for linking CTest).

Please show the error message

1 Like

You should not ever try to manually link object files emitted using --emit obj. Instead use --crate-type staticlib without --emit obj and link the .a static library that is generated. This bundles all rust dependencies your crate has.

You mean the .o files cannot be combined with .o files from another language (e.g. C or C++) and linked into one static library?

If you want a single static library, tell rustc to build a static library and then add the other object files to this static library. Or put the other object files in another static library and then tell rustc to bundle the contents of the former static library (this is the default when linking against static libraries).

Right that would work for Linux libraries or MinGW libraries (using ar), but is that possible for MSVC libraries?

llvm-ar should handle Windows static libraries produced by both MinGW and MSVC just fine.

Is there no native MSVC solution? I've never used LLVM.

Managing a Library | Microsoft Learn suggest that something like lib.exe /out:new_library.lib the_rustc_library.lib a.obj b.obj will create a library new_library.lib which has the contents of the_rustc_library.lib and also a.obj and b.obj added.

1 Like