How to track only C source files using gitignore configuration

I’m working on a project where I need to configure git to track only files with .c extension while ignoring everything else. I’ve been struggling with setting up the .gitignore file correctly to achieve this behavior.

I’ve consulted several AI tools for help but none of their suggestions worked for my setup. The responses I got didn’t produce the expected results when I tested them in my repository.

Can someone explain the proper way to configure .gitignore to exclusively manage C source files? I’m also curious about why the AI-generated solutions might have failed - could it be due to how I phrased my question or perhaps changes in git’s ignore syntax?

For reference, I’m currently running git version 2.39.2 on my system.

In my experience, the way to handle this is to first ignore everything by including * in your .gitignore. Then, to ensure that Git tracks your C source files, add !*.c. If you’re dealing with subdirectories, you’ll also want to include !*/ to allow Git to traverse into those folders and track any C files that you have there. So, your final .gitignore should have *, !*/, and !*.c. Many AI tools may overlook the directory structure, which can lead to the confusion you’re facing.

Yeah, classic gitignore gotcha. I’ve watched this trip up so many devs on my team.

AI solutions usually miss that gitignore rules have order dependency. Git reads top to bottom, so putting !*.c before handling directories breaks everything.

This works reliably:

# Ignore everything
*
# But descend into directories
!*/
# And track C files
!*.c

Watch out though - if Git’s already tracking files you want to ignore, run git rm --cached <file> first. Git won’t ignore stuff it’s already watching.

This setup tracks ALL .c files in your repo. Got build directories or temp folders with .c files you don’t want? Add specific ignores for those paths after these general rules.

I test this in throwaway repos first. Make some dummy files, apply the gitignore, then git status to see what gets picked up.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.