title: Is it possible to use C++20 modules in bazel with custom rules?
body: <p>Bazel does not have direct support for modules (See <a href="https://github.com/bazelbuild/bazel/issues/4005" rel="nofollow noreferrer">Issue #4005</a>).</p>
  <p>However, it is possible to provide bazel with a custom CROSSTOOL.</p>
  <p>From <a href="https://docs.bazel.build/versions/0.22.0/crosstool-reference.html" rel="nofollow noreferrer">https://docs.bazel.build/versions/0.22.0/crosstool-reference.html</a>:</p>
  <blockquote>
  <p>By default, Bazel automatically configures CROSSTOOL for your build, but you have the option to configure it manually.</p>
  </blockquote>
  <p>And it's possible to extend bazel with custom rules.</p>
  <p>From <a href="https://docs.bazel.build/versions/master/skylark/rules.html" rel="nofollow noreferrer">https://docs.bazel.build/versions/master/skylark/rules.html</a>:</p>
  <blockquote>
  <p>A few rules are built into Bazel itself. These native rules, such as cc_library and java_binary, provide some core support for certain languages. By defining your own rules, you can add similar support for languages and tools that Bazel does not support natively.</p>
  </blockquote>
  <p>And this <a href="https://github.com/bazelbuild/bazel/issues/4005#issuecomment-341682670" rel="nofollow noreferrer">comment</a> on Bazel's module issue suggests that you can use a custom CROSSTOOL to support modules even without native support:</p>
  <blockquote>
  <p>everything regarding modules (only for clang) is open sourced already. The only missing piece is a CROSSTOOL that makes use of them and provides all necessary features.</p>
  </blockquote>
  <p>Could anyone show how to write a custom CROSSTOOL for clang and how you can use it to write a custom C++ rule for modules (e.g. <code>cc_module</code>) so that you can do things like this:</p>
  <p>Write a basic module</p>
  <pre class="lang-cpp prettyprint-override"><code>// helloworld.cc
  module;
  #include &lt;stdio.h&gt;
  
  export module helloworld;
  export void hello();
  
  module :private;
  void hello() { puts(&quot;Hello world!&quot;); }
  </code></pre>
  <p>Use the module</p>
  <pre class="lang-cpp prettyprint-override"><code>// main.cc
  import helloworld;
  int main() { hello(); }
  </code></pre>
  <p>Integrate the parts into the build system</p>
  <pre class="lang-py prettyprint-override"><code>cc_module(
     name = &quot;helloworld&quot;,
     srcs = [&quot;helloworld.cc&quot;],
  ) # Compiles to a precomiled module file (PCM)
  
  cc_binary(
    name = &quot;main&quot;,
    srcs = [
      &quot;main.cc&quot;,
    ],
    deps = [
       &quot;:helloworld&quot;,
     ],
  ) # Compiles against the helloworld PCM
  </code></pre>