Bazel builds C++ dynamic link library so file

C++


Article directory


foreword

Bazel is a compilation tool open sourced by Google, which has the advantages of supporting multiple languages, fast compilation speed, convenient handling of dependencies, and simple compilation rules.

Some people say that bazel is a rogue tool, why? Because if one of your groups uses bazel, other groups must also use bazel in order to work together, otherwise the project as a whole cannot be managed.

This is true to a certain extent, because a project wants to be packaged as a whole. If one part is compiled with bazel and the other part is compiled with makefile, then these two parts cannot generate a complete dynamic link library for external use.

The next best thing is, is it acceptable for a project to provide multiple dynamic link library packages? If it is acceptable, it can also be managed when one part of the project is compiled with bazel and the other part is compiled with makefile. Because using bazel can generate the dynamic link library so file, makefile can also, put the two together, the problem will be solved.

This article briefly introduces the method of using bazel to generate C++ dynamic link library files.

The prerequisite knowledge required is:

  1. Familiar with gcc compilation and linking commands;
  2. Familiar with the use of bazel, know the role of WORKSPACE and BUILD files;
  3. Familiar with the rules of bazel, such as cc_binary, cc_import, you can refer to https://docs.bazel.build/versions/master/be/c-cpp.html

It is actually very simple to use bazel to generate a dynamic link library file. Just use the cc_binary rule. If you read the C++ rule file of bazel carefully, you will know that you only need to add such a rule:

cc_binary(
name = "libmylib.so", #mylib是头文件的名字
srcs = ["mylib.cpp",
    "mylib.h", #头文件和源文件,必须都有
],
deps = ["//XX:XX", #依赖,注意要把头文件和源文件中include的头文件所在的BUILD包都加进去
],
copts = ["-g", #编译时候的命令
],
linkopts = ["-lstdc++", #链接时候的命令
],
linkshared = True,
linkstatic = True,
)

After writing the above rules, run bazel build //XX:libmylib.so in the WORKSPACE directory to get the dynamically compiled library file of this project.

View link files for dynamically compiled library files. Enter ldd libmylib.so in the libmylib.so directory, and you can check where libmylib.so needs to find the lower-level dynamic link library files when it is called normally. You can install the corresponding dependencies in the new environment according to this directory, so that libmylib .so works fine.

Guess you like

Origin blog.csdn.net/zyq880625/article/details/131393651