How to set C++ standard version when build with Bazel?

bazel build --cxxopt='-std=c++11' main:hello-world This would work, but I wonder if there's way to set this cxxopt globally, like CMAKE_CXX_FLAGS.


To set the standard using the default C++ toolchain in Bazel you can set environment variable BAZEL_CXXOPTS, e.g. BAZEL_CXXOPTS="-std=c++14". You can also set it from the command line or from .bazelrc using --repo_env=BAZEL_CXXOPTS. : is the flag separator.

Alternatively you can pass --cxxopt to Bazel, or put it into .bazelrc, e.g. --cxxopt='-std=c++11'.

The robust solution to specifying C++ toolchain in Bazel is to use the CcToolchainConfigInfo. See the documentation at https://docs.bazel.build/versions/master/tutorial/cc-toolchain-config.html and https://docs.bazel.build/versions/master/cc-toolchain-config-reference.html.


Add this to your .bazelrc next to your WORKSPACE:

build --action_env=BAZEL_CXXOPTS="-std=c++20"

If you want to set multiple options, separate them with a colon:

build --action_env=BAZEL_CXXOPTS="-std=c++20:-Werror"

It is kind of a workaround as bazel sets an environment variable which bazel then uses. But it works.


BTW: build --cxxopt=-std=c++20 in the .bazelrc did not work form me.

Tags:

Bazel