Macros

Status: Stable

Macro creation

A macro is a function called from the BUILD file. It can instantiate native or Skylark rules. By the end of the loading phase, macros don't exist anymore: Bazel sees only the set of rules they created.

Native rules can be instantiated from the native module, e.g.

native.cc_library(name = x)

If you need to know the package name (i.e. which BUILD file is calling the macro), use the constant PACKAGE_NAME.

Examples

Debugging

  • bazel query --output=build //my/path:all will show you how the BUILD file looks like after evaluation. All macros, globs, loops are expanded.

  • You can also use print for debugging. It displays the message as a warning during the loading phase. Except in rare cases, remove your print calls before submitting the code to the depot.

Errors

If you want to throw an error, use the fail function. Explain clearly to the user what went wrong and how to fix their BUILD file. It is not possible to catch an error.

Conventions

  • All public functions (functions that don‘t start with underscore) that instantiate rules must have a name argument. This argument should not be optional (don’t give a default value).

  • Public functions should use a docstring following Python conventions.

  • In BUILD files, the name argument of the macros must a be a keyword argument (not a positional argument).

  • The name attribute of rules generated by a macro should include the name argument as a prefix. For example, macro(name = "foo") can generate a cc_library foo and a genrule foo_gen.

  • Macros should have an optional visibility argument.