title: Bazel - how to deal with transitive dependencies of external .so libraries?
body: <p>I'm trying to build a binary application with Bazel. This binary depends on an external, pre-compiled library, let's call it <code>liba.so</code>. In turn, <code>liba.so</code> depends on <code>libb.so</code> (this information I obtain via <code>readelf -d liba.so | grep NEEDED</code>.</p>
  <p>To build this, I have the following setup in Bazel:</p>
  <pre><code>cc_import(
      name = &quot;liba&quot;,
      shared_library = &quot;liba.so&quot;,
      deps = [&quot;:libb&quot;],
  )
  
  cc_import(
      name = &quot;libb&quot;,
      shared_library = &quot;libb.so&quot;,  
  )
  
  cc_binary(
      name = &quot;my_app&quot;,
      srcs = [&quot;main.cpp&quot;],
      deps = [&quot;:liba&quot;],
  )
  </code></pre>
  <p>Building works fine, however when running (either via <code>bazel run</code> or directly) <code>ldd</code> fails to find <code>libb.so</code>.</p>
  <p>I've been reading about this and the reason is that Bazel adds to the <code>RUNPATH</code> of the binary only its <strong>direct dependencies</strong>. Since <code>libb.so</code> is a transitive dependency, the binary cannot find it.</p>
  <p>To solve this, I can think of the following hacks:</p>
  <ul>
  <li><p>Add ugly linker flags to tell Bazel to add to the <code>RPATH</code> instead of <code>RUNPATH</code>. This is however deemed a bad idea, since <code>RPATH</code> is being deprecated and doesn't allow override via <code>LD_LIBRARY_PATH</code>.</p>
  </li>
  <li><p>Patch the third-party .so file to add to their <code>RUNPATH</code>. This works but it doesn't feel good to patch libraries I don't own.</p>
  </li>
  <li><p>Make the transitive dependencies direct dependencies of the binary. This is not good, each library should be responsible of its dependencies. The binary doesn't need to know what <code>liba.so</code> depends on.</p>
  </li>
  </ul>
  <p>Are there better ways to accomplish this? Other things I've tried without success:</p>
  <ul>
  <li>Use <code>cc_library</code> instead of <code>cc_import</code></li>
  <li>Use <code>data</code> instead of <code>deps</code>.</li>
  </ul>
  <p>Thanks!</p>