Description
Description
Building a program using printf does not work with the linker error LNK2019: unresolved external symbol printf referenced in function ...
A Minimum Working Example without any dependencies (except libc) that shows the issue
use libc::{c_char, printf};
fn main() {
unsafe {
printf(b"Hello World!\n\0" as *const u8 as *const c_char);
}
}
The target triple
x86_64-pc-windows-msvc
Instructions to reproduce
uploads to github gists, etc.)
- Create a new project with
cargo new reproduce
cd
./reproducecargo add libc
- copy the minimum example above in the main.rs file
cargo run
Further information
This issue apparently runs into the same problem.
From this microsoft documentation it seems that the bug depends on the Windows SDK version used:
If you are linking with Windows SDK 8.1 or earlier, you might encounter these unresolved external symbol errors. In that case, you should resolve the error by adding legacy_stdio_definitions.lib to the linker input as described previously.
I successfully tried the fix outlined in this comment by separating out the affected print
- and scan
- family functions (currently there are only the two functions printf
and fprintf
) into their own extern "C"
block and annotating that with #[cfg_attr(all(windows, target_env = "msvc"), link(name = "legacy_stdio_definitions", kind = "dylib"))]
.
According to this documentation from microsoft the "legacy_stdio_definitions.lib" is only supplied with Visual Studio 15 and later. I don't know if there is a way to detect at compile time the Visual Studio version used in the toolchain and only conditionally apply the fix I outlined above.