Emacs as C++ IDE, easy way

  |   Source

CREATED: <2016-08-25>

UPDATED: <2017-05-17 Wed>

This is a newbie friendly solution which works at Linux/OSX/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 ~/obj if the project/library directories are read only
cd /usr/include && MAKEOBJDIRPREFIX=~/obj gtags 
cd /usr/linux/include && MAKEOBJDIRPREFIX=~/obj gtags 
... 
# index files are placed inside the projects
cd ~/proj1 && gtags 
cd ~/proj2 && gtags
...

If you are using old Global (v5.7.1, for example), the command to create tags file in read only directory may fail. This is Global's bug. But there is workaround:

# dump index files to ~/obj if the project/library directories are read only
mkdir -p ~/obj/usr/include && cd /usr/include && gtags ~/obj/usr/include
mkdir -p ~/obj/usr/linux/include && cd /usr/linux/include && gtags ~/obj/usr/linux/include

Global introduced MAKEOBJDIRPREFIX on 2008-03-23.

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

;; Please note `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

Technical Details (Optional)

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

Comments powered by Disqus