How to compile c++ code with CMakeLists.txt inside using cc crate?

Hi folks,

I have a small cmake project (all files written in c++) and I want to compile it to use inside my Rust project (to check outputs from different crypto libraries and compare with output of my own). So, for this case I use cc crate and my build.rs looks like this:

fn main() {
    cc::Build::new()
        .cpp(true)
        .file("...")
        .file("...")
        .file("...")
        // ...
        .compile("main.a");
}

but the issue is that the project uses CMakeLists.txt for compilation, in particular, it uses the next instruction:

target_link_libraries(project ssl crypto)

which installs extra dependencies. And I didn't find how can I apply this CMakeLists.txt for building process inside my app.

Could somebody explain how to do this ?

cc is not intended for this, check out the cmake crate:

1 Like

after I built the project using cmake crate, I see success message in console output, but now it is not clear how to import the code.

My build.rs:

fn main() {
    let dst = cmake::Config::new("srp6_dir").build();

    println!("cargo:rustc-link-search=native={}", dst.display());
}

when I run the build I see no println! output from the code above, but build process has no errors and completed successfully.

In my c++ file I added extern "C" to the function which I want to use from Rust code:

// main.cpp
extern "C" int test_crypto(int argc, char* argv[]) {
    // ...
    return 0;
}

could you tell what am I doing wrong ? There no import by function name or by dir name where the file with this function is located

I think I found what I should do. First of all, I should add this instruction to the build.rs:

println!("cargo:rustc-link-lib=dylib=stdc++");

so this will use default compiler to link the function from c++.

Second, I should add smth like this to the Rust code:

extern "C" {
    #[link(name="stdc++", kind="static")]
    fn test_srp6(argc: i32, argv: *mut *mut c_char) -> c_int;
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.