- 1 year ago
how to bazel build a C++ windows executable w/o it needing vcruntime DLLs?
To build a C++ Windows executable using Bazel without it needing vcruntime DLLs, you can use the /MT
flag to statically link the C runtime libraries. This will embed the runtime code directly into your executable, eliminating the need for the vcruntime DLLs.
Here are the steps to configure Bazel to build a C++ executable without vcruntime DLL dependencies:
Open your project's
WORKSPACE
file or create one if it doesn't exist.Add the following lines to your
WORKSPACE
file to set the appropriate build settings:python# Define the msvc_toolchain configuration
load("@bazel_tools//tools/build_defs/repo:msvc_toolchain.bzl", "msvc_toolchain")
msvc_toolchain(
name = "my_msvc_toolchain",
target_cpu = "x64", # Modify if you need a different target CPU
additional_runtime_libraries = ["libcmt.lib"], # Add any additional libraries you may need
)
# Specify the msvc_toolchain as the default toolchain for the project
default_toolchain(name = "my_msvc_toolchain")
Open your project's
BUILD
file where you define the Bazel targets.Add the
linkstatic = 1
attribute to thecc_binary
target to enable static linking of the C runtime libraries. For example:pythoncc_binary(
name = "my_executable",
srcs = ["main.cc"],
linkstatic = 1,
)
Build your project using Bazel:
rubybazel build //path/to:my_executable
By setting the linkstatic
attribute to 1
in the cc_binary
target, Bazel will instruct the linker to statically link the C runtime libraries. This eliminates the need for vcruntime DLLs.
Note that static linking can increase the size of your executable, so consider the trade-offs carefully based on your specific requirements.
Please make sure to adjust the target CPU and additional libraries as needed, and consult Bazel's documentation for more information on using the MSVC toolchain and customizing build settings.