Help needed to solve compile and linkage issues


#1

Hello everyone,

I’m having difficulties to compile and link rust code to object one and link it against C one.

Those are the files:

mylib2.rs

extern crate libc;

use libc::{c_char, uint8_t};
use std::ffi::CString;
use std::iter;

#[no_mangle]
pub extern fn theme_song_generate(length: uint8_t) -> *mut c_char {
    let mut song = String::from(" ");
    song.extend(iter::repeat("na ").take(length as usize));
    song.push_str("Batman!");

    let c_str_song = CString::new(song).unwrap();
    c_str_song.into_raw()
}

#[no_mangle]
pub extern fn theme_song_free(s: *mut c_char) {
    unsafe {
        if s.is_null() { return }
        CString::from_raw(s)
    };
}

test2.c

#include <stdio.h>
#include <stdint.h>

extern char *
theme_song_generate(uint8_t length);

extern void
theme_song_free(char *);

int main(void) {
  char *song = theme_song_generate(5);
  printf("%s\n", song);
  theme_song_free(song);
}

Once I call rustc --emit=obj mylib2.rs I get the following errors

error: main function not found

error: use of unstable library feature 'libc': use `libc` from crates.io (see issue #27783)
 --> mylib2.rs:1:1
  |
1 | extern crate libc;
  | ^^^^^^^^^^^^^^^^^^

error: use of unstable library feature 'libc': use `libc` from crates.io (see issue #27783)
 --> mylib2.rs:3:12
  |
3 | use libc::{c_char, uint8_t};
  |            ^^^^^^

error: use of unstable library feature 'libc': use `libc` from crates.io (see issue #27783)
 --> mylib2.rs:3:20
  |
3 | use libc::{c_char, uint8_t};
  |                    ^^^^^^^

error: use of unstable library feature 'libc': use `libc` from crates.io (see issue #27783)
 --> mylib2.rs:8:43
  |
8 | pub extern fn theme_song_generate(length: uint8_t) -> *mut c_char {
  |                                           ^^^^^^^

error: use of unstable library feature 'libc': use `libc` from crates.io (see issue #27783)
 --> mylib2.rs:8:60
  |
8 | pub extern fn theme_song_generate(length: uint8_t) -> *mut c_char {
  |                                                            ^^^^^^

error: use of unstable library feature 'libc': use `libc` from crates.io (see issue #27783)
  --> mylib2.rs:18:39
   |
18 | pub extern fn theme_song_free(s: *mut c_char) {
   |                                       ^^^^^^

error: aborting due to 7 previous errors

#2

You don’t need libc for c_char and other C types:

use std::os::raw::c_char;

if you need C stdlib functions, then use libc from crates.io, i.e. add it to Cargo.toml.

“error: main function not found” means Rust thinks you’re building a Rust binary, not a C binary with Rust code. Remove [[bin]] and add [lib] to Cargo.toml.


#3

This command emits the intermediate objects, but still thinks it’s compiling an executable. Try either rustc --crate-type=staticlib or =cdylib to build your library for FFI linkage.


#4

Thank you guys !