Emacs as C++ IDE, easy way

  |   Source

CREATED: <2016-08-25 Thu>

UPDATED: <2018-12-04 Tue>

This solution works on Linux/macOS/Cygwin (should work at Windows too, but I don't develop at Windows).

Setup is minimum. Only GNU Global and two Emacs plugins are required:

Here is the step to step guide.

Step 1, create sample projects for experiment

I have two projects ~/proj1 and ~/proj2.

Both projects use files from read only directories /usr/include and /usr/src/linux/include.

We create a new directory ~/obj to store index files created by GNU Global because directories of third party libraries are read only.

Let's create directories,

mkdir -p ~/{proj1,proj2,obj}

The content of ~/proj2/lib.cpp,

void proj2_hello(int a2, char* b2) {
}

The content of ~/proj1/main.cpp,

void proj1_hello(int a1, char* b1) {
}

int main(int argc, char *argv[]) {
    return 0;
}

Step 2, scan C++ code and setup Emacs

Run below command in shell to scan code,

# dump index files to directory ~/obj if 3rd party library directory is read only
cd /usr/include && MAKEOBJDIRPREFIX=~/obj gtags --objdir
cd /usr/linux/include && MAKEOBJDIRPREFIX=~/obj gtags --objdir
# # above two command lines are same as below two command lines
# mkdir -p ~/obj/usr/include && cd /usr/include && gtags --objdir=~/obj/usr/include
# mkdir -p ~/obj/usr/linux/include && cd /usr/linux/include && gtags --objdir=~/obj/usr/linux/include
... 
# index files are placed inside the projects
cd ~/proj1 && gtags 
cd ~/proj2 && gtags
...

Global introduced MAKEOBJDIRPREFIX on 2008-03-23. I tested with GNU Global v6.6.2 on Debian.

After installing Emacs plugins and setup (minimum setup from their website is enough), insert below code into ~/.emacs,

;; `file-truename' MUST be used!
(setenv "GTAGSLIBPATH" (concat "/usr/include"
                               ":"
                               "/usr/src/linux/include"
                               ":"
                               (file-truename "~/proj2")
                               ":"
                               (file-truename "~/proj1")))
(setenv "MAKEOBJDIRPREFIX" (file-truename "~/obj/"))
(setq company-backends '((company-dabbrev-code company-gtags)))

Usage

Use the Emacs plugins as usual.

But you need install latest company built on 25th August because I fixed a company issue yesterday.

Screenshot,

cpp-gtags-demo-nq8.png

Tip

GNU Global could use ctags (Either Exuberant Ctags or Universal Ctags) as backend to create tags file.

I suggest NOT doing so. Or else I'm not sure the company-mode or emacs-counsel-gtags will work.

If you prefer ctags, you could use it directly. Then you can use company-etags.el from company-mode for auto-completion and counsel-etags for navigation instead.

Technical Details (Optional)

Check GNU Global manual to understand environment variables GTAGSLIBPATH and MAKEOBJDIRPREFIX.

Comments powered by Disqus