How GLSL Handles Single-Line Comments at Line Ends
This article provides a direct overview of how the OpenGL Shading Language (GLSL) compiler processes single-line comments at the end of physical file lines. It covers standard newline termination behavior, the interaction with backslash line continuations, edge cases at the end of a file (EOF), and potential pitfalls when using multiple source strings in OpenGL.
Standard Line Termination
GLSL adopts standard C++ conventions for single-line comments using
the // token. Once the compiler encounters //,
it ignores all subsequent characters up to the end of the current
physical line.
A physical line is terminated by any standard newline sequence recognized by GLSL:
- Line Feed (
\n, ASCII0x0A) - Carriage Return (
\r, ASCII0x0D) - Carriage Return followed by Line Feed (
\r\n)
When any of these line-break sequences is reached, the comment immediately ends. The newline itself is typically preserved in lexical analysis to increment the preprocessor's internal line counter, ensuring compiler diagnostics and error messages report the correct line numbers.
Line Continuations (\)
If a backslash (\) appears as the last character of a
physical line inside a single-line comment—immediately preceding the
newline character—the GLSL preprocessor treats it as a line
continuation.
The backslash and the subsequent newline character are deleted, splicing the two physical lines into a single logical line. Consequently, the single-line comment continues onto the next physical line, causing any code on that following line to be treated as part of the comment and discarded.
End of File Without a Trailing Newline
When a // comment is placed on the final line of a
shader source file and is not terminated by a newline before reaching
the end of the file (EOF), GLSL compilers treat the EOF as an implicit
line terminator.
The comment terminates safely without triggering syntax errors in modern compilers. However, because some older or strict embedded compilers may emit warnings or encounter parsing glitches when a file lacks a trailing newline, best practices recommend always terminating the final line of a GLSL file with a standard newline character.
Behavior in Multi-String Shader Sources
A common source of bugs occurs when passing an array of strings to
glShaderSource. OpenGL conceptually concatenates these
strings into a single translation unit.
If a string in the array ends with a // comment without
a trailing newline character (\n), the comment will extend
directly into the beginning of the next string in the array. This causes
the first line of the subsequent string to be commented out
unintentionally. To prevent this, every string containing single-line
comments must explicitly include a newline character before ending.