Linking with Xcode 9.2 OpenGL framework in CMake on Monterey

427 Views Asked by At

I have a peculiar setup, but necessary out of business decisions outside of my control.

I am running macOS 12 on Apple Silicon, have Xcode 9.2, am able to compile and link, by specifying the actual compilers inside the Xcode package, and specifying a more up to date version of ar and ranlib to CMake (the Xcode 9.2 versions give runtime errors on newer systems), basically like this:

-DCMAKE_C_COMPILER=/Applications/Xcode_10.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
-DCMAKE_CXX_COMPILER=/Applications/Xcode_10.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang++
-DCMAKE_OSX_SYSROOT=/Applications/Xcode_10.1.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk
-DCMAKE_OSX_ARCHITECTURES=x86_64
-DCMAKE_AR=/usr/bin/ar
-DCMAKE_RANLIB=/usr/bin/ranlib

These options work and let e.g. Xcode 10.1 tools be usable and we can build our software on newer OS versions, but in the XCode 9.2 case, we fail in linking OpenGL:

ld: can't map file, errno=22 file '/Applications/Xcode_9.2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/OpenGL.framework' for architecture x86_64

Due to the commandline option passed to Clang:

/Applications/Xcode_9.2.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks/OpenGL.framework

Which seems to think that it is a file, while it's a framework (directory). Changing this manually to

-framework OpenGL

makes everything work as expected. But that's not what CMake provides.

The question now is: how do I make CMake use this option instead of just passing the OpenGL framework directory path to Clang (with as little change to our CMake files as possible). We currently link any targets using OpenGL using the imported targets provided by find_package(OpenGL REQUIRED):

target_link_libraries(... PRIVATE OpenGL::GL)

And ideally I'd like to keep this the same as there's many of these in our solution.

UPDATE: I hit an additional snag, which seems to be that things like Qt5's cmake scripts are also adding the OpenGL framework directories outside of my OpenGL::GL usage. So perhaps a better approach would be to find a functional ar/ranlib on M1 that can handle what Xcode 9.2's ar/ranlib can handle.

1

There are 1 best solutions below

1
On

If you want to link specifically with -framework OpenGL, you should change your target_link_libraries line to look like this instead:

target_link_libraries(${PROJECT_NAME} LINK_PUBLIC "-framework OpenGL")

I believe this removes the need for find_package(OpenGL) as well.