user3701366
user3701366

Reputation: 474

How can I link a system library statically in Bazel?

How can I link a system library statically in mostly static mode (linkstatic=1)? I tried to use "-Wl,-Bstatic -lboost_thread -Wl,-Bdynamic" or "-Wl,-Bstatic", "-lboost_thread", "-Wl,-Bdynamic", but none of them worked. I don't want to hard code the path of libboost_thread.a in the system.

cc_binary(
    name = "main",
    srcs = [
        "main.cpp",
    ],
    linkopts = [
        "-lboost_thread",
    ],
)

And boost_thread library is linked as a dynamic library.

ldd bazel-bin/main
linux-vdso.so.1
libboost_thread.so.1.54.0 => /usr/lib/x86_64-linux-gnu/libboost_thread.so.1.54.0
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
...

Upvotes: 12

Views: 15698

Answers (2)

user3701366
user3701366

Reputation: 474

Based on the answer in this question, Telling gcc directly to link a library statically, "-l:libboost_thread.a" will link the system library statically, without hard coding the path of libboost_thread.a in the system.

cc_binary(
    name = "main",
    srcs = [
        "main.cpp",
    ],
    linkopts = [
        "-l:libboost_thread.a",
        "-l:libboost_system.a",
    ],
)

Upvotes: -1

Francis Hitchens
Francis Hitchens

Reputation: 147

In your WORKSPACE file define an external repository...

new_local_repository(
    name = "boost_thread",
    path = "/usr/lib/x86_64-linux-gnu",
    build_file = "boost_thread.BUILD"
)

Create a boost_thread.BUILD file

cc_library(
   name = "lib",
   srcs = ["libboost_thread.a"],
   visibility = ["//visibility:public"],
)

Then in your cc_binary rule add

deps = ["@boost_thread//:lib",],

and throw in a

linkstatic = 1

to be on the safe side.

Upvotes: 13

Related Questions