Coolest C Preprocessor Trick of the Year

Probably everyone knew about this but me, but here goes anyway. (hat tip: Google's ANGLE library)

By suitably defining SHADER_SOURCE, you can write your shader program as though it was just inline source in your larger C(++) program:

const char * fs = SHADER_SOURCE
        (
            precision mediump float;
            void main()
            {
                gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
            }
        );

The definition of SHADER_SOURCE is simple:

#define SHADER_SOURCE(...) # __VA_ARGS__

This works as long as your shader is a valid sequence of preprocessor tokens. If you need to also use shader language directives like #version, you will need to write them as strings. But due to the way string catenation works, you can do

const char * fs =
    "#version 100\n"
    SHADER_SOURCE(...);
and keep most of the inline shader source outside of strings.

Entry first conceived on 30 December 2015, 19:38 UTC, last modified on 30 December 2015, 22:09 UTC
Website Copyright © 2004-2017 Jeff Epler