Search code examples
cross-platformglutbazel

platform dependent linker flags in bazel (for glut)


I am trying to build the c++ app with glut using bazel. It should work on both macos and linux. Now the problem is that on macos it requires passing "-framework OpenGL", "-framework GLUT" to linker flags, while on linux I should probably do soemthing like cc_library( name = "glut", srcs = glob(["local/lib/libglut*.dylib", "lib/libglut*.so"]), ... in glut.BUILD. So the question is 1. How to provide platform-dependent linker options to cc_library rules in general? 2. And in particular how to link to glut in platform-independent way using bazel?


Solution

  • You can do this using the Bazel select() function. Something like this might work:

    config_setting(
        name = "linux_x86_64",
        values = {"cpu": "k8"},
        visibility = ["//visibility:public"],
    )
    
    config_setting(
        name = "darwin_x86_64",
        values = {"cpu": "darwin_x86_64"},
        visibility = ["//visibility:public"],
    )
    
    cc_library(
        name = "glut",
        srcs = select({
            ":darwin_x86_64": [],
            ":linux_x86_64": glob(["local/lib/libglut*.dylib", "lib/libglut*.so"]),
        }),
        linkopts = select({
            ":darwin_x86_64": [
                "-framework OpenGL",
                 "-framework GLUT"
            ],
            ":linux_x86_64": [],
        })
        ...
    )
    

    Dig around in the Bazel github repository, it's got some good real world examples of using select().