Blog

Integrating flatbuffers into Visual Studio

For a recent project I wanted to automate the process of generating flatbuffers to make it as frictionaless as possible to work with flatbuffer schema files. The final process I settled on was to extend visual studio using some new configuration files. The result was a process that worked like so:

  1. Manually add a flatbuffer .fbs to the VS project (VS automatically recognizes the type)
  2. Build the project like normal, VS runs a custom pre-build event to generate the header file

I experimented with some additional features like auto-including .fbs files from a directory or automatically including the generated header files in the project but I opted to be explicit instead.

My configuration for Visual Studio 2017

I created a flatbuffers.xml that registers the filetype:

<?xml version="1.0" encoding="utf-8"?>
<ProjectSchemaDefinitions 
        xmlns="http://schemas.microsoft.com/build/2009/properties"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <ItemType Name="Flatbuffer" DisplayName="Flattbuffer Schema" />
    <ContentType Name="FlatBuffer" DisplayName="Flatbufer Schema" ItemType="FlatBuffer" />
    <FileExtension Name="*.fbs" ContentType="Flatbuffer" />
</ProjectSchemaDefinitions>

I created a flatbuffers.target that defines the custom build event for the .fbs files:

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <ItemGroup>
        <PropertyPageSchema Include="$(MSBuildThisFileDirectory)flatbuffers.xml" />
        <AvailableItemName Include="Flatbuffer">
            <Targets>Flatbuffers</Targets>
        </AvailableItemName>
    </ItemGroup>
    <Target 
        Name="Flatbuffers" 
        BeforeTargets="ClCompile">

        <Message Importance="High" Text="Compiling flatbuffer files..." />

        <ItemGroup>
            <Flatbuffer>
                <Message>-- Compiling %(Filename)%(Extension)</Message>
                <Command>$(SolutionDir)bin\$(Configuration)\thirdparty\flatc.exe --cpp --gen-object-api -o $(ProjectDir)%(RelativeDir) %(Fullpath)</Command>
                <Outputs>%(Filename)_generated.h</Outputs>
            </Flatbuffer>
        </ItemGroup>

        <CustomBuild
            Sources="@(Flatbuffer)"
            MinimalRebuildFromTracking="true"
            TrackerLogDirectory="$(TLogLocation)"/>
    </Target>
</Project>

Finally, I modified my projects .vcxproj file to import the new targets

....
<ImportGroup Label="ExtensionTargets">
    <Import Project="flatbuffers.targets" />
</ImportGroup>

NOTE This is what the item ended up looking like in the .vcxproj file after I added it in visual studio:

...
<ItemGroup>
    <FlatBuffer Include="myschema.fbs" />
</ItemGroup>
....