如何在 MacOS 上的 clion 上为 glfw 正确设置 cmake

How to correctly setup cmake for glfw on clion on MacOS

我最近买了一台 Macbook,我想开始为项目编写一些 OpenGL 代码。

规格

CMake 没有报错,但我一开始编译就收到以下错误

    /Applications/CLion.app/Contents/bin/cmake/mac/bin/cmake --build /Users/arnesix/Documents/dev/c++/graphics/cmake-build-debug --target graphics -- -j 12
[ 50%] Linking CXX executable graphics
Undefined symbols for architecture x86_64:
  "_CFArrayAppendValue", referenced from:
      __glfwInitJoysticksNS in libglfw3.a(cocoa_joystick.m.o)
      _matchCallback in libglfw3.a(cocoa_joystick.m.o)
  "_CFArrayCreateMutable", referenced from:
      __glfwInitJoysticksNS in libglfw3.a(cocoa_joystick.m.o)
      _matchCallback in libglfw3.a(cocoa_joystick.m.o)
  "_CFArrayGetCount", referenced from:
      __glfwSetVideoModeNS in libglfw3.a(cocoa_monitor.m.o)
      __glfwPlatformGetVideoModes in libglfw3.a(cocoa_monitor.m.o)
      _matchCallback in libglfw3.a(cocoa_joystick.m.o)
      _closeJoystick in libglfw3.a(cocoa_joystick.m.o)
      __glfwPlatformPollJoystick in libglfw3.a(cocoa_joystick.m.o)
  "_CFArrayGetValueAtIndex", referenced from:
      __glfwSetVideoModeNS in libglfw3.a(cocoa_monitor.m.o)
      __glfwPlatformGetVideoModes in libglfw3.a(cocoa_monitor.m.o)
      _matchCallback in libglfw3.a(cocoa_joystick.m.o)
      _closeJoystick in libglfw3.a(cocoa_joystick.m.o)
      __glfwPlatformPollJoystick in libglfw3.a(cocoa_joystick.m.o)
  "_CFArraySortValues", referenced from:
      _matchCallback in libglfw3.a(cocoa_joystick.m.o)

我从 https://www.glfw.org/download.html 下载的二进制文件只包含 64 位二进制文​​件。

我正在使用以下 cmake 代码和文件夹结构

#include <iostream>
#include <glfw3.h>

int main() {
    std::cout << glfwInit() << std::endl;
    return 0;
}

最后,我的 Cmake 偏好

我很想知道为什么会这样,我应该如何解决这个问题。

你读过the documentation了吗?如果您这样编译,您将缺少三个框架:

target_link_libraries(graphics glfw3 -framework Cocoa -framework OpenGL -framework IOKit)

最好只使用 the find_package approach

我遇到了完全相同的问题。
我正在使用 local(不是系统范围)glfwglad
这是我最终得到的对我有用的 cmake 文件。

cmake_minimum_required(VERSION 3.17)
project(project_name)

set(CMAKE_CXX_STANDARD 14)
if (APPLE)
    set(CMAKE_CXX_FLAGS "-framework Cocoa -framework IOKit")
    # -framework OpenGL -framework CoreVideo
    add_compile_definitions(GL_SILENCE_DEPRECATION)
endif ()

include_directories(<your include dir here>)
add_executable(project_name <your source files here>)

target_link_libraries(project_name <path to libglfw3.a>)

真正帮助我的是set(CMAKE_CXX_FLAGS "-framework Cocoa -framework IOKit")

GL_SILENCE_DEPRECATION部分似乎没有影响,所以可以忽略。