Skip to content

Commit

Permalink
When linking mostly-static Linux binaries, link libstdc++.a explicitly.
Browse files Browse the repository at this point in the history
This allows libstdc++ to be statically linked, which is normally only
possible when invoking GCC as `g++` with the `-static-libstdc++` flag.

Fixes bazelbuild#2840

See envoyproxy/envoy#415 for additional
background and context.
  • Loading branch information
jmillikin-stripe committed Nov 12, 2017
1 parent 67c84b1 commit ffe40ea
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
1 change: 1 addition & 0 deletions tools/cpp/CROSSTOOL.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ toolchain {
%{opt_content}
}
linking_mode_flags { mode: DYNAMIC }
%{link_content}

%{coverage}
}
Expand Down
20 changes: 19 additions & 1 deletion tools/cpp/unix_cc_configure.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,24 @@ def _build_crosstool(d, prefix=" "):
return "\n".join(lines)


def _build_link_content():
# `-static-libstdc++` is only supported when invoking GCC as `g++`, and
# `-lstdc++` forces dynamic linking of libstdc++. To get desired
# mostly-static behavior, invoke the link by explicitly naming a static
# library archive.
#
# https://github.com/bazelbuild/bazel/issues/2840
return """
linking_mode_flags {
mode: DYNAMIC
linker_flag: "-lstdc++"
}
linking_mode_flags {
mode: MOSTLY_STATIC
linker_flag: "-l:libstdc++.a"
}"""


def _build_tool_path(d):
"""Build the list of %-escaped tool_path for the CROSSTOOL file."""
lines = []
Expand Down Expand Up @@ -174,7 +192,6 @@ def _crosstool_content(repository_ctx, cc, cpu_value, darwin):
"-std=c++0x",
] + _escaped_cplus_include_paths(repository_ctx),
"linker_flag": [
"-lstdc++",
"-lm", # Some systems expect -lm in addition to -lstdc++
# Anticipated future default.
] + (
Expand Down Expand Up @@ -385,6 +402,7 @@ def configure_unix_toolchain(repository_ctx, cpu_value):
_build_tool_path(tool_paths),
"%{opt_content}": _build_crosstool(opt_content, " "),
"%{dbg_content}": _build_crosstool(dbg_content, " "),
"%{link_content}": _build_link_content(),
"%{cxx_builtin_include_directory}": "",
"%{coverage}": _coverage_feature(darwin),
"%{msvc_env_tmp}": "",
Expand Down
1 change: 1 addition & 0 deletions tools/cpp/windows_cc_configure.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ def configure_windows_toolchain(repository_ctx):
"%{content}": _get_escaped_windows_msys_crosstool_content(repository_ctx),
"%{opt_content}": "",
"%{dbg_content}": "",
"%{link_content}": "",
"%{cxx_builtin_include_directory}": "",
"%{coverage}": "",
})
Expand Down

0 comments on commit ffe40ea

Please sign in to comment.