Cloud Stack Ninja

Is it possible to use C++20 modules with bazel?

Bazel does not have direct support for modules (See Issue #4005).

However, it is possible to provide bazel with a custom CROSSTOOL.

From https://docs.bazel.build/versions/0.22.0/crosstool-reference.html:

By default, Bazel automatically configures CROSSTOOL for your build, but you have the option to configure it manually.

And it possible to extend bazel with custom rules.

From https://docs.bazel.build/versions/master/skylark/rules.html:

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.

And this comment on Bazel's module issue suggests that it's possible to use a custom CROSSTOOL to support modules even without native support:

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.

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. cc_module) so that you can do things like this:

Write a basic module

// helloworld.cc
module;
#include <stdio.h>

export module helloworld;
export void hello();

module :private;
void hello() { puts("Hello world!"); }

Use the module

// main.cc
import helloworld;
int main() { hello(); }

Integrate the parts into the build system

cc_module(
   name = "helloworld",
   srcs = ["helloworld.cc"],
) # Compiles to a precomiled module file (PCM)

cc_binary(
  name = "main",
  srcs = [
    "main.cc",
  ],
  deps = [
     ":helloworld",
   ],
) # Compiles against the helloworld PCM


Read more here: https://stackoverflow.com/questions/64406726/how-can-you-use-bazel-with-c20-modules

Content Attribution

This content was originally published by Ryan Burn at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: