Daniel Fath
Daniel Fath

Reputation: 18069

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.

Upvotes: 2

Views: 1776

Answers (3)

tpimh
tpimh

Reputation: 578

I think, cargo-c is excatly what you are looking for:

It produces and installs a correct pkg-config file, a static library and a dynamic library, and a C header to be used by any C (and C-compatible) software.

Upvotes: 0

Daniel Fath
Daniel Fath

Reputation: 18069

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.

Upvotes: 0

Steve Klabnik
Steve Klabnik

Reputation: 15539

Is there any way Cargo can create this C library for me?

Cargo does not currently have this feature.

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

Is there a reason that it is in C? C can call into Rust code directly, you could just use html5ever as it exists.

Upvotes: 1

Related Questions