Search Unity

Use a #define macro as path in #include directive in shader?

Discussion in 'Shaders' started by stephero, Dec 29, 2018.

  1. stephero

    stephero

    Joined:
    Feb 8, 2016
    Posts:
    123
    Hi guys,

    In a Unity shader, it doesn't seem to be possible to do the following:
    Code (CSharp):
    1. #define MYMACRO "UnityCG.cginc"
    2. #include MYMACRO
    It fails to compile:
    Code (CSharp):
    1. Shader error in '***': syntax error : unexpected token 'MYMACRO'
    Do you why it's not possible to use a macro in an include preprocessor directive?
    Is there a way to do something similar?

    Thanks
     
  2. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    This is because of how #include and c style preprocessor macros work.

    My understanding of how it goes is something like this.

    Step 1: load .shader text.
    Step 2: scan text for the first #include line and find the appropriate file.
    Step 3: load the text from the found file. insert that text into the previously loaded code at the position the #include for it existed.
    Step 4: Repeat steps 1 through 3 until no #include lines are found.

    Note, at no point yet has the text been parsed or compiled in any way beyond just looking for those #inlcude lines. This is just building one big giant file with all of the include files inlined into the shader. Imagine manually going through and replacing all of your #include lines with the code copy/pasted from those files. That’s all it’s doing.

    Step 5 then takes that one giant file and probably looks for #pragma multi_compile lines and other ShaderLab specific stuff, then Step 6 and beyond is actually parsing the #if and #define lines to generate code variants before eventually compiling those many shader variants.

    TLDR version, #include lines are parsed before #define lines, so it doesn’t yet know what that MYMACRO is supposed to be something else.
     
    jtianyoozoo and SugoiDev like this.
  3. stephero

    stephero

    Joined:
    Feb 8, 2016
    Posts:
    123
    Thanks for your reply.
    The weird thing is that it works in C++.
    That's why I was wondering why the behavior is different in shader lab.
    Thanks
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,348
    Well, this isn’t c++, or even c, it’s just something Unity implemented themselves in the same written style as c.
     
    stephero likes this.