3

I'm writing a C++ application that has source files in a source directory, within which there is a build directory. The build directory contains the Makefile, so when I build the program I do so from the build directory.

I want git to ignore the build directory because it doesn't contain source files. However, I do want git to track the Makefile. What's the best practice for tracking the Makefile but ignoring the other build files? Should I be using another directory structure?

Thanks!

8bittree
  • 1,769
  • 2
  • 18
  • 25
Travis G.
  • 218
  • 2
  • 9

2 Answers2

6

You can tell git to not ignore certain files in .gitignore by prepending ! to a pattern. So you could put a .gitignore file in your build directory with content like this:

# Ignore everything in this directory
*
# Except this file and the Makefile
!.gitignore
!Makefile

To give credit where I think credit is due, this is probably where I first learned about these exceptions.

Community
  • 1
  • 1
8bittree
  • 1,769
  • 2
  • 18
  • 25
  • Ah, I had been using my root-level .gitignore to ignore the whole build directory, so I was having trouble telling git not to ignore the Makefile within the build directory. The separate .gitignore file solves it for me. – Travis G. Oct 19 '15 at 01:53
3

Ignore rules are just for file git does not already know about, and you can also git add any file by specifying it's name.

So, just git add the Makefile, and add an ignore rule to ignore build/

You could place a .gitignore file in build/ with pattern *

Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
  • While this answer is entirely correct, it does not address the problem of an accidental deletion of the Makefile, which, if committed, would make it harder to add it again in a subsequent commit. Better be explicit and use a .gitignore exception. – SirDarius Oct 16 '15 at 20:22
  • Well... You can add ignored files just like any other file both from command line and GUIs. – Johan Lundberg Oct 16 '15 at 20:29