c file is only compiled when it is used by add_subdirectory

I have a C++ project with a .c and .cpp file:

# d:\top\sub\CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(foo CXX)
add_executable(foo WIN32 file1.cpp file2.c)

when generating a vcxproj the .c file gets listed as NONE and is not compiled:

<!-- generated by: cmake -G "Visual Studio 14 2015" d:\top\sub -->
<ItemGroup>
  <ClCompile Include="D:\uniplot\sub\file1.cpp" />
  <None Include="D:\uniplot\sub\file2.c" />
</ItemGroup>

While tracking down the issue, I noted that when I put a parent CMakeLists on top and use add_subdirectory() the file gets listed as CICompile and it works:

# d:\top\CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(top)
add_subdirectory(sub)

generates

<!-- generated by: cmake -G "Visual Studio 14 2015" d:\top -->
<ItemGroup>
  <ClCompile Include="D:\uniplot\sub\file1.cpp" />
  <ClCompile Include="D:\uniplot\sub\file2.c">
    <CompileAs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">CompileAsC</CompileAs>
    <CompileAs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">CompileAsC</CompileAs>
    <CompileAs Condition="'$(Configuration)|$(Platform)'=='MinSizeRel|Win32'">CompileAsC</CompileAs>
    <CompileAs Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'">CompileAsC</CompileAs>
  </ClCompile>
</ItemGroup>

How can I make it work without the parent/outer layer?

I may be wrong but the issue may come from the fact that you’ve limited your project to C++ compiler only.
In the case where you use add_subdirectory you leave project languages to default which means C & C++ and this is why it works in that case.

I changed it to project(foo CXX C) and it seems to work.