编译Cherno OpenGL项目时遇/usr/bin/ld: -f需搭配-shared使用错误
解决编译Cherno OpenGL教程代码时的链接错误
错误原因分析
你遇到的-f may not be used without -shared错误,本质是编译命令中混入了macOS特有的链接选项,而Linux下的clang无法正确解析这些选项。从你给出的编译命令能看到,链接阶段加入了-framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo——这些是苹果系统专用的框架链接方式,Linux环境下不支持,clang会把这些选项误解析成非法的-f开头参数,从而触发链接错误。
具体解决步骤
修改Makefile中的链接选项
找到Makefile里负责链接生成app的那一行(对应你给出的第二条clang++命令),删除所有-framework开头的选项,替换成Linux下OpenGL的标准链接参数-lGL。修改后的链接命令大致如下:clang++ -std=c++11 -I/home/john/Music/fastapi/thecherno_opengl/ep22-imgui -I/home/john/Music/fastapi/thecherno_opengl/ep22-imgui/../external -I/home/john/Music/fastapi/thecherno_opengl/ep22-imgui/vendor/imgui -I/home/john/Music/fastapi/thecherno_opengl/ep22-imgui/vendor/stb_image -DDEBUG -g -L/home/john/Music/fastapi/thecherno_opengl/ep22-imgui/../lib -lglfw3 -lGLEW -lGL -o app Application.o IndexBuffer.o Renderer.o Shader.o Texture.o VertexArray.o VertexBuffer.o vendor/imgui/imgui.o vendor/imgui/imgui_demo.o vendor/imgui/imgui_draw.o vendor/imgui/imgui_impl_glfw_gl3.o vendor/stb_image/stb_image.o确保Linux依赖已安装
如果你还没安装OpenGL、GLFW、GLEW的开发库,执行以下命令(Debian/Ubuntu系):sudo apt update && sudo apt install libglfw3-dev libglew-dev libgl1-mesa-dev重新编译
先清理之前生成的目标文件,再重新执行make:make clean && make
额外排查点
如果修改后仍报错,检查Makefile中是否有拼写错误的编译选项,比如不小心把某个选项写成-f开头但未完成(比如-f后面漏了参数),或者空格错位导致选项解析异常。
内容的提问来源于stack exchange,提问作者NooB Programmer
相关产品推荐
相关产品推荐

