Mac OSX 11.4下OpenGL 3.3着色器编译失败问题求助(设备明明支持3.3版本却提示不兼容)
Hey there, let's break down why you're hitting those shader compilation errors even though your hardware supports OpenGL 3.3. I spotted a couple of critical issues in your code that are causing this:
1. GLFW Window Hint Order Is Wrong (The Big Culprit)
Look at your main function: you're calling glfwCreateWindow before setting the OpenGL version and profile hints. GLFW window hints only apply to windows created after the hints are set—so your current code is creating a window with the default (older) OpenGL context, which doesn't support GLSL 330. That's exactly why you're getting the "version '330' is not supported" error.
Fix:
Move all your glfwWindowHint calls before glfwCreateWindow:
int main(int argc, char **argv) { if (!glfwInit()) { std::cerr << "GLFW init failed..." << std::endl; return -1; } // Set OpenGL context hints FIRST, before creating the window glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE); // Now create the window with the correct context settings GLFWwindow *window = glfwCreateWindow(1280, 720, "A-Engine", nullptr, nullptr); if (window == nullptr) { std::cerr << "Window init failed..." << std::endl; glfwTerminate(); return -2; } // Rest of your code remains the same... }
2. Frag Shader Filename Mismatch (Confusing, Not Critical But Fixable)
You named your fragment shader fragShader.vert—that's the extension for vertex shaders. While this won't break compilation directly, it's easy to mix up files later. Rename it to fragShader.frag and update the path in your createAndLinkShader function:
std::string FragmentShader = "/fragShader.frag";
3. Add Error Handling to Shader File Reads
Your readFile function returns an empty string if the file fails to open, which will cause weird syntax errors in the shader compiler (since it's trying to compile an empty source). Let's add proper error checking here:
std::string readFile(const std::string &fileLoc) { std::ifstream file(fileLoc); if (!file.is_open()) { std::cerr << "Failed to open shader file: " << fileLoc << std::endl; exit(-4); } std::stringstream context; context << file.rdbuf(); return context.str(); }
This way, if your shader files are missing or in the wrong path, you'll get a clear error message instead of confusing shader syntax errors.
Quick Recap of Steps to Fix:
- Rearrange GLFW window hints to come before window creation.
- Fix the fragment shader filename and corresponding path in code.
- Add error handling to ensure shader files are loaded correctly.
Once you make these changes, your OpenGL 3.3 context will be properly created, and your shaders should compile without the version/syntax errors.
内容的提问来源于stack exchange,提问作者Marcin Wawrzków

