I understood from the book, to call a "C" function, we need to:
Define the function name and signature in a extern "C" block, as:
extern "C" {
fn abs(input: i32) -> i32;
}
Execute the function using unsafe block, as:
unsafe {
println!("Absolute value of -3 according to C: {}", abs(-3));
}
// OR
println!("Absolute value of -3 according to C: {}", unsafe { abs(-3) } );
This is if we are calling a C standard function, but what if I want to have my custom C function, for example, I've the below C code:
#include <stdio.h>
int twice(int);
int main(void) {
printf("Hello World: %d\n", twice(2));
return 0;
}
int twice(int x) {
return x * 2;
}
What will be the replacement Rust code:
extern "C" { // extern block
fn twice(input: i32) -> i32; // function name and signature
}
println!("Twice value of 3 according to C: {}", unsafe { twice(3) } ); // execute in unsafe block
But what about the twice function itself, where and how or what shall I do with the:
You donβt need extern on the C function. Thatβs telling the C compiler the definition of that function is provided externally, and will be resolved by the linker.
The C function can just be what @hyousef wrote initially. That function (or rather its source file, aka translation unit) needs to be compiled (by a C compiler) into, using linux as example, a static lib (eg libfoo.a) or a shared lib (eg libfoo.so). Then that lib needs to be linked to by rustc during its compilation.