背景:Mac m1环境,macOS Ventura 13.0.1系统,使用VScode,用cmake编译c++文件,使用OpenGL库
gcc 版本
(base) yuwenshuo@Cosmos-Computer build % gcc --version
Apple clang version 14.0.0 (clang-1400.0.29.202)
Target: arm64-apple-darwin22.1.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
遇到的现象:生成的执行文件HelloGL无法打开
o@Cosmos-Computer build % ./HelloGL
freeglut (./HelloGL): failed to open display ''
具体main.cpp代码如下
#include<stdio.h>
#include<GLUT/glut.h>
void displayMe(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glVertex3f(0.5, 0.0, 0.5);
glVertex3f(0.5, 0.0, 0.0);
glVertex3f(0.0, 0.5, 0.0);
glVertex3f(0.0, 0.0, 0.5);
glEnd();
glFlush();
}
int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowSize(400, 300);
glutInitWindowPosition(100, 100);
glutCreateWindow("Hello world!");
glutDisplayFunc(displayMe);
glutMainLoop();
//return 0;
}
编写的CmakeLists.txt文件内容如下:
cmake_minimum_required(VERSION 3.0.0)
project(HelloGL VERSION 0.1.0)
# 使用 C++ 11 标准
set(CMAKE_CXX_STANDARD 11)
# 添加头文件
set(GLAD_H ${PROJECT_SOURCE_DIR}/include)
set(GLFW_H /opt/homebrew/Cellar/glfw/3.3.8/include)
set(GLUT_H /opt/homebrew/Cellar/freeglut/3.2.2/include)
include_directories(${GLAD_H} ${GLFW_H} ${GLUT_H})
# 添加目标链接
set(GLFW_LINK /opt/homebrew/Cellar/glfw/3.3.8/lib/libglfw.3.dylib)
set(GLUT_LINK /opt/homebrew/Cellar/freeglut/3.2.2/lib/libglut.3.dylib)
link_libraries(${GLFW_LINK} ${GLUT_LINK})
# 执行编译命令
set(SOURCES glad.c main.cpp)
add_executable(HelloGL ${SOURCES})
# 链接系统的 OpenGL 框架
if (APPLE)
target_link_libraries(HelloGL "-framework OpenGL")
endif()
include(CTest)
enable_testing()
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
我的解答思路和尝试过的方法:
(base) o@Cosmos-Computer build % export DISPLAY=localhost:1
(base) yuwenshuo@Cosmos-Computer build % ./HelloGL
freeglut (./HelloGL): failed to open display 'localhost:1'
(base) o@Cosmos-Computer build % export DISPLAY=0
(base) o@Cosmos-Computer build % ./HelloGL
freeglut (./HelloGL): failed to open display '0'
(base) o@Cosmos-Computer build % export DISPLAY=
(base) o@Cosmos-Computer build % ./HelloGL
freeglut (./HelloGL): failed to open display ''
可见大概不是host的问题