GNU global is a very
compelling way to quickly search your project from the command line. Here I
show how to index your code and update it automatically when using git.
Indexing your code
To index your code, simply run the following in your project root directory:
This will parse your code for tags and create the database files GPATH,
GRTAGS and GTAGS. It's blazing fast, too: A project with several million
lines of code took only seven seconds on my workstation.
For C++ projects, note that gtags may interpret .h files as C code. You can
fix that up with ~/.globalrc, but so far I haven't had any big problem with
Querying the code
Now that you have indexed your project, you can query for specific tags by
typing global name. For example, to see the definition for value_t, just
Add -x to get a code excerpt:
To see where value_t is referenced, add -r:
You can also use -g to grep, so you don't have to spell out the correct name:
You can also use regular expressions with -e. See man global for many other
Pro tip: Create an alias for global:
There is also the gtags-cscope utility. It lets you interactively search for
stuff and open an editor. I'm not sure I'll be using it much, but it's there.
Automatically syncing gtags on git updates
At work, I've set up so that the tag-files are automatically updated whenever
git changes the files on disk, for example when I fetch and checkout,
cherry-pick and so on. I'll show how to do that.
First, add GPATH, GRTAGS and GTAGS to .gitignore:
Next, you need to set up some git hooks. The whole approach here is taken from
Effortless Ctags with
Git by Tim
Pope, and slightly modified to work with GNU global.
Put the below script in .git/hooks/gtags:
Unfortunately, GNU global doesn't allow relative paths in the environment
variable GTAGSROOT, so we can't store the database under .git.
Put the following in post-commit, post-merge, post-checkout:
Notice that it runs gtags in the background, which is nice.
Put this in post-rewrite:
For an explanation of the above hooks, look at the post by Tim Pope above. It
suggests putting them in a git template directory, which means they are
automatically copied over to new or cloned repositories.
Finally, make them executable:
Now, whenever you checkout etc., the index will be updated.
As Tim Pope writes, you can even create a command git gtags so you can update
This lets you do
to manually update the database. However, if you have only changed a few files
and want to re-index, you might be better off using global -u to perform an
update. It could be faster.