C++ how to static link to openssl using bazel

Viewed 44

Currently I link to openssl as shared_library with my C++ program, like this in bazel BUILD file:

linkopts = [
                   "-lssl",
                   "-lcrypto",
                ],

but the openssl version of deploy machine is not the same with my compile machine, so I want to link staticlly to openssl library, but I dont know how...

1 Answers

By far the best way to do this is to make use of bazelbuild/rules_foreign_cc. There is even an example of how to do this here. Now the easiest way to do this is to copy the example directory from the rules_foreign_cc repository. e.g.

git clone https://github.com/bazelbuild/rules_foreign_cc.git
cp -r rules_foreign_cc/examples/third_party/openssl ~/my_workspace/

Then you can load the dependencies like so;

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "rules_foreign_cc",
    sha256 = "2a4d07cd64b0719b39a7c12218a3e507672b82a97b98c6a89d38565894cf7c51",
    strip_prefix = "rules_foreign_cc-0.9.0",
    url = "https://github.com/bazelbuild/rules_foreign_cc/archive/refs/tags/0.9.0.tar.gz",
)

load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies")

# This sets up some common toolchains for building targets. For more details, please see
# https://bazelbuild.github.io/rules_foreign_cc/0.9.0/flatten.html#rules_foreign_cc_dependencies
rules_foreign_cc_dependencies()

# file: //:WORKSPACE
load("//openssl:openssl_repositories.bzl", "openssl_repositories")
openssl_repositories()

load("//openssl:openssl_setup.bzl", "openssl_setup")
openssl_setup()

You can of course modify the copied files to meet your specific needs and configuration if you so choose.

To depend on openssl you simply add it as a dependency like any other Bazel dep e.g.

cc_binary(
   name = "depends_on_openssl",
   srcs = ["depends_on_openssl.c"],
   deps = ["@openssl//:openssl"],
)
Related