GLSL #error Directive for Compile Validation
The #error preprocessor directive in GLSL provides
developers with a fail-fast mechanism that halts shader compilation and
emits a custom diagnostic message when critical compile-time conditions
are not met. This article explains the primary role of the
#error directive in validating shader configurations,
enforcing required macros, handling platform-specific constraints, and
preventing hard-to-debug runtime rendering anomalies.
What Is the #error
Directive?
In the OpenGL Shading Language (GLSL), the #error
directive instructs the preprocessor to immediately abort the
compilation process. When encountered, the GLSL compiler terminates
compilation and appends the user-defined message following the directive
directly into the shader's compilation log. Developers can retrieve this
diagnostic output via standard OpenGL API calls, such as
glGetShaderInfoLog.
Enforcing Preprocessor Configurations
Modern graphics pipelines frequently use multi-variant
"uber-shaders," where feature sets, rendering paths, and quality
settings are controlled via preprocessor macros passed at compile time.
The #error directive ensures that mandatory definitions
exist before the compiler attempts to process the core shader logic.
#version 450 core
#ifndef LIGHT_COUNT
#error "LIGHT_COUNT must be defined before compiling this shader."
#endif
#if LIGHT_COUNT > 64
#error "LIGHT_COUNT exceeds the maximum supported capacity of 64."
#endifIf the host application fails to provide LIGHT_COUNT, or
passes an unsupported value, compilation halts immediately with a clear,
actionable explanation rather than failing downstream with cryptic
syntax errors or undeclared identifier warnings.
Validating Mutually Exclusive Flags
Complex shaders often contain configurations that cannot legally
coexist. The #error directive allows developers to define
explicit conflict boundaries:
#if defined(FORWARD_RENDERING) && defined(DEFERRED_RENDERING)
#error "Conflicting rendering paths: choose either FORWARD_RENDERING or DEFERRED_RENDERING."
#endifThis prevents invalid shader permutations from compiling, safeguarding against undefined runtime states.
Verifying Extension and Hardware Requirements
While the #extension directive handles enabling specific
hardware features, the #error directive can validate that
an essential extension is supported before code relying on that feature
compiles:
#extension GL_EXT_shader_explicit_arithmetic_types : enable
#ifndef GL_EXT_shader_explicit_arithmetic_types
#error "GL_EXT_shader_explicit_arithmetic_types is required for this shader."
#endifKey Advantages of Using
#error
- Immediate Failure: Catches configuration mistakes at the earliest possible stage in the asset pipeline or engine initialization.
- Readable Diagnostics: Replaces ambiguous parsing errors with descriptive, engineer-defined messages.
- Elimination of Silent Fallbacks: Guarantees that shaders do not build with incomplete or mismatched macro configurations.