[swift-users] Swift can’t compile code with OpenGL function pointers

Joe Groff jgroff at apple.com
Thu Mar 30 11:31:01 CDT 2017

> On Mar 30, 2017, at 7:47 AM, Kelvin Ma via swift-users <swift-users at swift.org> wrote:
> OpenGL functions are loaded at runtime by a function loader (like GLFW). They’re defined in a header but obviously they don’t have definitions at compile time so it causes a slew of linker errors when I try to build
>     error: undefined reference to 'glEnable'
>     error: undefined reference to 'glBlendFunc'
>     error: undefined reference to 'glClearColor'
>     clang: error: linker command failed with exit code 1 (use -v to see invocation)
>     ...
> How do I build programs that use OpenGL functions?

If the functions are exported by the OpenGL library you're linking against, then you may need to just use -lGL to link against it. That's not likely to be portable, though, since implementations vary in what they statically export. The macro metaprogramming used by GLFW and other libraries to dynamically load GL entry points is probably not going to get picked up by Swift's C importer, so you'd need to roll your own solution. Something like this might work as a start:

func loadGLFunction<T>(name: String) -> T {
#if os(macOS)
  return unsafeBitCast(dlsym(RTLD_DEFAULT, name), to: T.self)
#elseif os(Linux)
  return unsafeBitCast(glXGetProcAddress(name), to: T.self)
#elseif os(Windows)
  return unsafeBitCast(wglGetProcAddress(name), to: T.self)

enum GL {
  static let begin: @convention(c) (GLenum) -> Void = loadGLFunction("glBegin")
  static let end: @convention(c) () -> Void = loadGLFunction("glEnd")


More information about the swift-users mailing list