Feasibility of integrating Clang into Cargo

Would it be possible to extend Cargo so that it could be used to compile C and C++ code (using Clang under the hood)?
What would be great is if we could express a dependency on a C library and have Cargo download the source, compile it and link against it. It could even be used to make a C/C++ binary, with or without Rust dependencies. This could have a lot of benefits:

  1. Cargo could become the de-facto C/C++ package manager, especially if it made compiling C++ code across platforms as easy as Rust is today.
  2. Rust code that depends on existing libraries would be easier to deal with (although I have heard rumblings that this is already getting easier).
  3. C/C++ projects could use Rust crates more conveniently.
  4. Even more pie-in-the-sky, if the C/C++ code was compiled down to a .dylib, (or to LLVM byte code, if that's not what a .dylib is) then you could get whole-program optimizations, and maybe it would be easier to expose one type of code as if it was the other. (Like calling a .NET assembly written in VB from a C# assembly.)

A few specific points/questions:

  • I am not asking for someone to do this for me, I am just asking if it would be feasible.
  • What would be the biggest obstacles? (I mean specifically. Saying "It would be way way hard!" while true, is not the answer I am looking for.)
  • What about Cargo and Rust enables simpler cross platform development than C/C++? would this be able to translate over, or are issues like the C++ ABI not being specified too big to overcome? (Seems like if we are working with source, or .dylibs, Cargo could just pick a C++ ABI and use that across all platforms.)
  • Is somebody already working on something similar to this?
3 Likes

I already do this in my crates.

You create a cargo crate (preferably with a -sys name suffix) with a build.rs script that uses the cc crate to build C code. Cargo picks it up automatically and links with the rest of the project.

For exporting to C there's crate-type staticlib and cdylib, which can be used by gcc and clang. It works very well. All C tools that I use (lldb, kcov, Xcode's instruments) support C and Rust mixed together seamlessly.

5 Likes

Wow, I had no idea about the cc crate. I will have to look into this more!
Thanks.