Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple .c source files with Rust [duplicate]

Tags:

rust

I am successfully using a .c file with Rust (see this answer). How can I link multiple .c files? I've already tried #![link_args="/c_src/*.c"] with no luck.

- rust-demo
  - src
    - c_src
      - file1.c
      - file2.c
      - etc...
    - main.rs

Edit:

I think a better question would be, how can I simply drop the C source code in my Rust directory and start using it directly by using Rust's link attribute & extern (or any other way) with the above example in mind?

like image 377
goo Avatar asked Oct 17 '25 11:10

goo


2 Answers

how can I simply drop the C source code in my Rust directory and start using it directly by using Rust's link attribute & extern (or any other way)

You can't just put C code into Rust sources and expect it to work. As said in the comments of your other question, the syntax #![link_args="foo.c"] has never be planned to work, and you should not rely on that.

The only thing Rust code can be linked against (except other rust code) is a compiled library (static or dynamic). You need to compile your C files into one or several libraries before being able to call them from your Rust code.

The proper way to do so is adding a build argument in the [package] section of your Cargo.toml, you can thus invoke a makefile that will first build your C files into a static library, and then link your Rust code against it.

All details are provided on the cargo website : http://doc.crates.io/build-script.html

like image 69
Levans Avatar answered Oct 22 '25 02:10

Levans


Assuming you're using Cargo, add some sort of script with build = ["gcc ..."] to build them into a proper library, then you only have one thing to specify in #[link_args]

like image 33
o11c Avatar answered Oct 22 '25 01:10

o11c



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!