简体   繁体   中英

Playing with Bazel C++ tutorials; build does not create/use shared libraries?

Looking at Bazel today for the first time.

On building the cpp tutorial , I can see how it builds simple executables and archive libraries, but it doesn't look like the examples create or use shared libraries.

Does anyone know of simple example BUILD files to demonstrate this process? Thanks.

A shared library is a cc_binary :

cc_binary(
    name = "libfoo.so",
    srcs = ["foo.cc"],
    linkshared = 1,     ## important
)

(In non-trivial situations, you should probably also add linkstatic = 1 to get a self-contained DSO that does not itself have load-time dependencies on its source dependencies.)

In order to perform dynamic linking, you must first import the shared library. You should specify the library headers, the library binary and the interface library (required for Windows only, not present in this example):

# Build the shared library
cc_binary(
    name = "libfoo.so",
    srcs = ["foo.cc"],
    linkshared = 1,     ## important
)

# Import the shared library
cc_import(
    name = "imported_libfoo",
    hdrs = ["foo.h"],
    shared_library = "libfoo.so",
)

# Link to the shared library
cc_binary(
    name = "bar",
    deps = [":imported_libfoo"],
)

Based on the above method, I add a little exception.

Take an example above, if you so library also deps on another cc_library , do add alwayslink = True to the cc_library , otherwise the shared library will not have a symlink.

cc_library(
    name = "hello-greet-lib",
    srcs = ["hello-greet.cc"],
    hdrs = ["hello-greet.h"],
    alwayslink = True,   # important
)

cc_binary(
    name = "libhello-greet.so",  # the shared library
    linkshared = True,
    deps = [":hello-greet-lib"],
)

cc_import(
    name = "hello-greet",
    shared_library = "libhello-greet.so",
    hdrs = ["hello-greet.h"],
)

cc_binary(
    name = "hello-world",
    srcs = ["hello-world.cc"],
    deps = [
        ":hello-greet",
        "//lib:hello-time",
    ],
)

this is common when you need to aggregate some libraries, so do remember add alwayslink = True if you want to generate the dynamic library in the above way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM