# Share a function between two passes inside CG Shader for unity3d

I'm writing a shader in CG language for Unity3d. When making transparent object you need to create two similar passes in SubShader. First to render only back faces (with Cull Front) and second to render only front faces (with Cull Back). But the code for vertex and fragment function is the same.

Is it possible not to double a code and declare some functions, that would be shared between passes?
I want to have something like in my code example.

Shader "cool shader" {
Properties {
...
}

CGPROGRAM
// need to declare vertexOutput somewhow here
float4 sharedFragFoo(vertexOutput i) : COLOR  // How to make smth like this?
{
....
return float4(...);
}
ENDCG

pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
vertexOutput vert(vertexInput v) {
vertexOutput o;
...
return o;
}

float4 frag(vertexOutput i) : COLOR
{
return sharedFragFoo(i); // call the shared between passes function
}

ENDCG
}

pass {
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
vertexOutput vert(vertexInput v) {
vertexOutput o;
...
return o;
}

float4 frag(vertexOutput i) : COLOR
{
return sharedFragFoo(i); // call the shared between passes function
}

ENDCG
}
}
}

• Have you looked into the #include directive? I use that to share functions from Unity's libraries all the time, so presumably it could be used with custom files (not making this an answer because I haven't confirmed it works, or details of where to put the .cginc file) – DMGregory May 29 '15 at 12:25

We can define all that lies between CGPROGRAM and ENDCG in separate *.cginc file and include it inside each pass.