Bazel rules and utilities to generate C++ source files that embed arbitrary binary/text files as array literals.
Minimal Example
In Bazel, add this module as a dependency and use the included cc_embed macro to define a cc_library target that you
can link against.
# MODULE.bazel bazel_dep(name = "tsnl.cc_embed") git_override( module_name = "tsnl.cc_embed", remote = "https://github.com/tsnl/cc_embed", branch = "main", )
# BUILD.bazel load("@tsnl.cc_embed//:bazel/defs.bzl", "cc_embed") cc_embed(name = "embedded_resource", data_file = "data/example.bin") # ...
The above invocation of cc_embed will generate this header file (along with the backing source file containing the
data):
// Auto-generated by embed_cpp, do not edit #pragma once #include <span> #include <cstddef> namespace tsnl::embed_cpp { extern std::span<const std::byte> embedded_resource; } // namespace tsnl::embed_cpp
The variable tsnl::cc_embed::embedded_resource is now accessible in your binary/library by...
- Adding the
"embedded_resource"target as a dependency in Bazel. - Including the
<tsnl/cc_embed/embedded_resource.hpp>header.
# BUILD.bazel # ... cc_binary(name = "hello_world", srcs = ["main.cpp"], deps = [":embedded_resource"])
// main.cpp #include <tsnl/cc_embed/embedded_resource.hpp> auto main(int argc, char const* argv[]) -> int { tsnl::cc_embed::embedded_resource; }