Search code examples
static-librariesrustrust-cargoc-api

Is there a way to create C library with Cargo?


I need to create a (static) C library that binds to existing crate. Is there any way Cargo can create this C library for me?

I have a crate (e.g. html5ever), and I want Cargo to create a C library based on C-API for that crate.


Solution

  • A way to solve this problem is to create a special crate which stores your C API. For example if your library is called foo, then have inside your main directory another folder alongside src/tests called capi, which will store a special crate foo_capi for C API.

      foo
       |
       +--src
       | 
       +--test
       |
       +--capi
            | 
            +--include 
            |
            +--src 
            |
            Cargo.toml
    

    include folder contains header files for C.

    src contains the Rust files which are exported into C.

    The Cargo manifest should be statically linked and have a dependency on the project foo. For example check out this Cargo.toml used in html5ever.