How to call Rust Library or rust functions in C Project


#1

Hello,

I just want to call/use the rust library or rust functions from rs file in C project. How can i implement it in eclipse ???
I have tried from several ways but didn’t get success.

below are the things, i did for achieving my target :----

  1. I created a new C project in eclipse having the “hello world” program. I am able to run the same.

  2. Now i created a rust file in the same src folder say lib.rs and write the below function in that file.

lib.rs :-

#![crate_type = “staticlib”]

#[no_mangle]
pub extern fn addition(x:i32,y:i32) ->i32 {
println!(“In Add function !”);
return x+y;
}

  1. I wanted to call that function from C’s main. so i code for the same, as below

#include <stdio.h>
#include <stdlib.h>

extern int addition( int x, int y);

int main() {
puts("!!!Welcome to the C World!!!");
int sum ;

sum = addition(10,5);
printf("addition is := %d", sum);

}

I am getting “undefined reference to `addition’” error when trying to build the project.

how can i get rid of from this error ???


#2

Probably the main problem here is the order of the file you are using during the link phase.

Imagine that you created the libadd.a with rust and main.o in C. main.o must precede libadd.a in the linker command.

But the fact is that, in this way, you will get many errors. This because you are creating a static library, and when you link together your files, you will miss many symbols. That’s because you are using the rust stdlib with the println! macro, and at to date we don’t have a pure rust ecosystem.

If you are on linux (sorry, that’s my OS :smile:) you can manually link the pthread and the dl libraries during the link phase. But if you use cdynlib instead of staticlib, you already have the resolution of your symbols, and you can just link the libadd.so (or libadd.dll on windows) to your C project. But I don’t know if it is your case :slightly_smiling_face:


#3

Does Eclipse know to compile the Rust code? If it’s a C project, then perhaps Eclipse is ignoring the .rs file?

In general this approach should work and your source code looks ok.


#4

Thanks for Response :slight_smile:
If Eclipse will ignore the .rs files, it means we cannot user rust libraries in our C/C++ projects, right ???

Is There any alternate way to use Rust libs in C/C++ projects ???


#5

You can use ‘rustc’ to build your crate as a static or dynamic library and then link with it. I do not use eclipse and I don’t know what build system you’re using so I don’t have specific advice. If you have a cmake project then I could paste some of what I use to integrate cargo into my cmake projects.

There was recently mentioned a new eclipse plugin for Rust called Corrosion. I’d venture to guess that it would be worth trying this out as a solution.