Set file name as project name in VS template

989 Views Asked by At

I've been trying to make my own template in VS for C++. I want to have a cpp and hpp file with the same name as the project. I have already read this link: How can I set a file name using a variable in a Visual Studio project template

Howerer, when using my template, the files are not in the project that I've created.

Here is my vstemplate file:

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Project">
  <TemplateData>
    <Name>My Template</Name>
    <Description>A test template</Description>
    <ProjectType>VC</ProjectType>
    <ProjectSubType>
    </ProjectSubType>
    <SortOrder>1000</SortOrder>
    <CreateNewFolder>true</CreateNewFolder>
    <DefaultName>MyProject</DefaultName>
    <ProvideDefaultName>true</ProvideDefaultName>
    <LocationField>Enabled</LocationField>
    <EnableLocationBrowseButton>true</EnableLocationBrowseButton>
    <Icon>__TemplateIcon.png</Icon>
    <PreviewImage>__PreviewImage.png</PreviewImage>
  </TemplateData>
  <TemplateContent>
    <Project TargetFileName="MyTemplate.vcxproj" File="MyTemplate.vcxproj" ReplaceParameters="true">
      <ProjectItem ReplaceParameters="true" TargetFileName="$safeprojectname$.vcxproj.filters">MyTemplate.vcxproj.filters</ProjectItem>
      <ProjectItem ReplaceParameters="true" TargetFileName="$safeprojectname$.cpp">MyFile.cpp</ProjectItem>
      <ProjectItem ReplaceParameters="true" TargetFileName="$safeprojectname$.hpp">MyFile.hpp</ProjectItem>
  </TemplateContent>
</VSTemplate>

What am I doing wrong?

Edit: Managed to figure it out, had to replace file names in vcxproj file itself. Thanks for helping!

2

There are 2 best solutions below

1
On BEST ANSWER

I ended up succeeding using the following method:

  • I added two files to my template, named $safeprojectname$.hpp and $safeprojectname$.cpp.
  • I edited my vcxproj file (using notepad++, or any other text editor for that matter), adding the following tags inside of the main Project tag:
  <ItemGroup>
    <ClInclude Include="%24safeprojectname%24.hpp" />
  </ItemGroup>
  <ItemGroup>
    <ClCompile Include="%24safeprojectname%24.cpp" />
  </ItemGroup>

I had to use %24 as $ is not a valid character in this context, and 24 is the ASCII (/unicode) value of that character.

0
On

Use the following method:

  1. Edit template file:
<ProjectItem 
  ReplaceParameters="false" 
  OpenInEditor="true" 
  TargetFileName="$safeprojectname$.cpp"
>
  task.cpp
</ProjectItem>

Replace the filename, not including the extension, with $safeprojectname$.

  1. Edit vcxproj file:
<ItemGroup>
  <ClCompile Include="$(RootNamespace).cpp" />
</ItemGroup>

Find the <ItemGroup> section with the file name and replace it, not including the extension, with $(RootNamespace).

File task.vcxproj.filters may be deleted.