How to add rules for gittgnore so that git ignore all types of files exept one type

I have a C++ project. I want to push it on GitHub. In that project there is many types of files. But I want to have only .cpp files on my GitHub repository.

So, how can I set the rules for it thus only .cpp files upload to GitHub rather than all other files.


Solution 1:

You cannot just ignore everything: that would ignore folders as well, which means any exception (!...) rule would be ignored. Any folder ignored means rules applying to files inside that folder will not apply.

That is what your .gitignore must make an exception for folders first.

*
!.gitignore
!**/
!*.cpp

!*.h
!*.hpp

For a more complete gitignore: gitignore.io, which takes the opposite approach: only specify what you want to ignore, track everything else.

Solution 2:

# Ignore everything
*

# Except
!*.cpp