bazelbuild / rules_foreign_cc

Build rules for interfacing with "foreign" (non-Bazel) build systems (CMake, configure-make, GNU Make, boost, ninja, Meson)
https://bazelbuild.github.io/rules_foreign_cc
Apache License 2.0
649 stars 232 forks source link

Bazel cmake rule overrides CMake build flag [CMAKE_CXX_COMPILER]. #1126

Open Frank-Michel opened 7 months ago

Frank-Michel commented 7 months ago

I am trying to build OpenCV on a Ubuntu 22.04 machine running Bazel 6.1.1. My workspace is setup as follows:

WORKSPACE:

http_archive(
    name = "rules_foreign_cc",
    sha256 = "476303bd0f1b04cc311fc258f1708a5f6ef82d3091e53fd1977fa20383425a6a",
    strip_prefix = "rules_foreign_cc-0.10.1",
    url = "https://github.com/bazelbuild/rules_foreign_cc/releases/download/0.10.1/rules_foreign_cc-0.10.1.tar.gz",)

load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies")

rules_foreign_cc_dependencies()

http_archive(
    name = "opencv",
    build_file = "//tools:opencv.BUILD",
    sha256 = "62f650467a60a38794d681ae7e66e3e8cfba38f445e0bf87867e2f2cdc8be9d5",
    strip_prefix = "opencv-4.8.1",
    urls = ["https://github.com/opencv/opencv/archive/refs/tags/4.8.1.tar.gz"],
)

opencv.BUILD:

load("@rules_foreign_cc//foreign_cc:defs.bzl", "cmake")

filegroup(
    name = "all_srcs",
    srcs = glob(["**"]),
)

cmake(
    name = "opencv",
    build_args = [
        "-j16",
    ],
    cache_entries = {
        "CMAKE_CXX_COMPILER": "g++",
        "CMAKE_CXX_STANDARD": "17",
        "BUILD_opencv_world": "ON",
        "BUILD_SHARED_LIBS": "ON",
    },
    env = {
        "CMAKE_BUILD_TYPE": "Release",
        "CMAKE_BUILD_PARALLEL_LEVEL": "16",
    },
    linkopts = [
        "-lstdc++",
    ],
    lib_source = "all_srcs",
    out_include_dir = "include/opencv4",
    out_shared_libs = ["libopencv_world.so"],
    visibility = ["//visibility:public"],
)

Trying to build the workspace CMake fails to build OpenCV and I see the following errors (and many more of the same kind):

/usr/bin/ld: /usr/include/c++/11/bits/basic_string.tcc:212: undefined reference to `std::__throw_logic_error(char const*)'

/usr/include/c++/11/ext/new_allocator.h:145: undefined reference to `operator delete(void*, unsigned long)'

/usr/include/c++/11/bits/basic_ios.h:462: undefined reference to `std::ios_base::ios_base()'

Checking Bazel's build log I noticed that in the CMake configuration both the C and the C++ compiler point to /usr/bin/gcc and I tried to change that by not relying on the default CMake configuration but by directly setting the C++ compiler to use g++. While setting the CMAKE_CXX_STANDARD changed the CMake output from 11 to 17 setting CMAKE_CXX_COMPILER does not change the CMake configuration at all.

I was able to reproduce this issue building OpenCV only using CMake without Bazel and setting the CMAKE_CXX_COMPILER to gcc.