title: Failing to use CXX to link Rust-written library in C++ project
body: <p>I am testing <a href="https://cxx.rs/index.html" rel="nofollow noreferrer">CXX</a> with a very simple project to link a Rust library into a C++ executable.</p>
  <p>I write a <code>foo() -&gt; ()</code> Rust function and try to access it from C++ but the linker does not find it.</p>
  <p>Here's what I have:</p>
  <pre class="lang-rust prettyprint-override"><code>// lib.rs
  
  #[cxx::bridge]
  mod ffi {
      extern &quot;Rust&quot; {
          pub fn foo() -&gt; ();
      }
  }
  
  pub fn foo() -&gt; () {
      println!(&quot;foo&quot;)
  }
  </code></pre>
  <pre class="lang-toml prettyprint-override"><code># Cargo.toml
  [package]
  name = &quot;cpprust&quot;
  version = &quot;0.1.0&quot;
  edition = &quot;2021&quot;
  
  [lib]
  name = &quot;cpprust&quot;
  path = &quot;src/lib.rs&quot;
  crate-type = [&quot;staticlib&quot;, &quot;rlib&quot;, &quot;dylib&quot;] # EDIT: this is incorrect, see note at the end of question
  
  # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
  
  [dependencies]
  cxx = &quot;1.0&quot;
  </code></pre>
  <pre class="lang-cpp prettyprint-override"><code>// main.cpp
  
  void foo(); // I tried including lib.rs.h but it was not generated!
  
  int main() {
      foo();
  }
  </code></pre>
  <p>Running <code>cargo build</code> generates <code>target\debug\libcpprust.so</code>.
  I then try to make the project with (EDIT: <code>g++</code> command is incorrect, see note at the end of question):</p>
  <pre class="lang-plain prettyprint-override"><code>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
  </code></pre>
  <p>What is wrong here?</p>
  <p><strong>EDIT</strong>: prog-fh's great answer correctly points out that I need to include <code>build.rs</code> with C++ compilation, even without having C++ to compile and access within the crate. However, even after implementing their answer, I was still getting the same error message. It turns out that I had two other problems: 1) the <em>order</em> of my arguments to <code>g++</code> were incorrect, and I needed <code>pthread -l dl</code> as well. It should have been:
  <code>g++ -o cpprust main.cpp -I ../target/cxxbridge -L../target/debug -lcpprust -pthread -l dl</code>
  2) My <code>Cargo.toml</code> file was also generating <code>&quot;rlib&quot;, &quot;dylib&quot;</code> library types, but that somehow also causes the error above; it works when only <code>staticlib</code> is generated.</p>