cxx icon indicating copy to clipboard operation
cxx copied to clipboard

Symbol not defined if I build without running cxx's code generator

Open rodrigodesalvobraz opened this issue 3 years ago • 2 comments

I am testing CXX with a very simple project to link a Rust library into a C++ executable.

I write a foo() -> () Rust function and try to access it from C++ but the linker does not find it.

Here's what I have:

// lib.rs

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        pub fn foo() -> ();
    }
}

pub fn foo() -> () {
    println!("foo")
}
# Cargo.toml
[package]
name = "cpprust"
version = "0.1.0"
edition = "2021"

[lib]
name = "cpprust"
path = "src/lib.rs"
crate-type = ["staticlib", "rlib", "dylib"]

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
cxx = "1.0"
// main.cpp

void foo(); // tried including lib.rs.h but it was not generated (why not?)

int main() {
    foo();
}

Running cargo build generates target\debug\libcpprust.so. I then try to make the project with:

g++ -L../target/debug/ -lcpprust -o cpprust main.cpp
/tmp/ccOA8kJy.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `foo()'
collect2: error: ld returned 1 exit status
make: *** [Makefile:2: cpprust] Error 1

What is wrong here?

rodrigodesalvobraz avatar Feb 13 '22 04:02 rodrigodesalvobraz

None of what you've written runs cxx's code generator.

If you aren't using one of the supported build systems, https://cxx.rs/build/other.html describes the list of things you would need to be responsible for.

dtolnay avatar Feb 14 '22 05:02 dtolnay

Thanks, I thought [cxx-bridge] was going to be enough to run the generator, and that the code in build.rs was necessary only if I had C++ code I wanted compiled by Cargo (because it uses cc which I thought was aimed at C/C++ only). More info at StackOverflow.

rodrigodesalvobraz avatar Feb 14 '22 06:02 rodrigodesalvobraz