In your .csproj, set Defines on the shader’s <OneShader> item. OneShader.Build adds these items by default.
dotnet add package RecursiveAI.OneShader.BuildRequires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.
<OneShader Include="Fill.hlsl" Defines="TILE_X=8" />
Unzip the example, then dotnet run.
This compiles Fill.hlsl (in the zip) with eight threads along X instead of four. The C# program prints Threads X: 8.
Input: Fill.hlsl. Save it beside the project file. #ifndef defines a fallback only if the build hasn’t provided TILE_X.
#ifndef TILE_X #define TILE_X 4 #endif RWStructuredBuffer<uint> Output : register(u0); [shader("compute")] [numthreads(TILE_X, 1, 1)] void CSMain(uint3 id : SV_DispatchThreadID) { Output[id.x] = id.x; }
The full program
Set <RootNamespace>Example</RootNamespace> in the project’s <PropertyGroup> as in the zip. OneShader.Build generates Example.Shaders.Fill. The C# program reads the generated thread count; it doesn’t need a GPU.
using Example.Shaders; Console.WriteLine($"Threads X: {Fill.CSMain.ThreadGroupSizeX}");
Threads X: 8If a macro leaves invalid HLSL after substitution, dotnet build reports the error at the HLSL line.
Variations
Project-wide define. Remove the per-file Defines attribute and set OneShaderDefines in a project property group instead. This example then prints Threads X: 16.
<PropertyGroup> <OneShaderDefines>TILE_X=16</OneShaderDefines> </PropertyGroup>
Related recipes
The short answer
For HLSL compiled by RecursiveAI.OneShader.Build, add Defines to the <OneShader> item in your .csproj. Use NAME=VALUE for a value and separate multiple definitions with semicolons. The generated bindings guide shows the attribute syntax, Defines="A;B=2". An explicit item doesn’t compile the file twice; the default glob skips shaders you list yourself.
Which HLSL preprocessor directive defines a macro?
Inside a shader, #define defines a macro. Use it in the source file if the value belongs to the shader itself. To share a source file between different projects, keep a default under #ifndef and supply the value through MSBuild where you need a different one. Without #ifndef here, the source would try to define TILE_X even when the build already supplied it. With the guard, the unchanged shader works with or without the item metadata.
How do you pass a preprocessor define through MSBuild?
Use item metadata for a value intended for one shader, or use OneShaderDefines for all shaders built by the project. This is separate from C# preprocessor symbols: DefineConstants controls conditional compilation in C#, not the HLSL build in this example. If your define changes the shader interface or thread count, read the corresponding generated C# members after rebuilding instead of duplicating the value in the host program. That’s how the example can distinguish eight threads from the four-thread fallback without running the shader.