简体   繁体   English

玩 Bazel C++ 教程; build 不创建/使用共享库?

[英]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.在构建cpp 教程时,我可以看到它如何构建简单的可执行文件和存档库,但它看起来不像示例创建或使用共享库。

Does anyone know of simple example BUILD files to demonstrate this process?有谁知道简单的示例 BUILD 文件来演示这个过程? Thanks.谢谢。

A shared library is a cc_binary :共享库是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.) (在非平凡的情况下,您可能还应该添加linkstatic = 1以获得一个独立的 DSO,它本身在其源依赖项上没有加载时依赖项。)

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):您应该指定库头、库二进制文件和接口库(仅 Windows 需要,本示例中不存在):

# 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 ,请添加alwayslink = Truecc_library ,否则共享库将没有符号链接。

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这在您需要聚合一些库时很常见,所以如果您想以上述方式生成动态库,请记住添加alwayslink = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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