Emacs CC Mode

This document adds some extra notes on setting up and using the CC Mode in Emacs. See the CC Mode section of the Emacs manual which provides extensive documentation of the mode.

Changing the Build Directory

In some situations, you may want to build outside the source directory.

When running the compile command, simply change it to pass the appropriate parameters to make. E.g.:

make -C ../build -k

Another option is to view the build directory in dired mode and run the compile command:

M-x compile

Customising Styles

There are primarily two aspects to setting up code formatting in Emacs CC Mode:

  1. Indentation

  2. Brace positioning (or 'hanging braces')

When following the documentation on these subjects, changing indentation is relatively straight-forward. However, changing the behviour of hanging braces is not so straight-forward.

It seems, that if a style has been set while customising the c-hanging-braces-alist variable, the changes have no effect. Therefore, the best approach is to comment out any set-style calls in the .emacs startup-file, re-start Emacs, customize the behaviour and save it for future sessions.

You need to toggle the c-toggle-auto-newline variable with M-x c-toggle-auto-newline to see how hanging braces behave during typing.

Once the behaviour is satisfactory, the entries in .emacs can be copied from the custom-set-variables entry to your own style entry. E.g.

;; Create my personal style based on k&r
(defconst my-cpp-style
  '("k&r" (c-tab-always-indent        . t)
    (c-hanging-braces-alist . ((defun-open after)
                               (class-open after)
                               (class-close before)
                               (inline-open)
                               (inline-close)
                               (block-close . c-snug-do-while)
                               (statement-cont)
                               (substatement-open after)
                               (brace-list-open)
                               (brace-entry-open)
                               (extern-lang-open after)
                               (namespace-open after)
                               (module-open after)
                               (composition-open after)
                               (inexpr-class-open after)
                               (inexpr-class-close before)
                               (arglist-cont-nonempty)))
    (c-echo-syntactic-information-p . t))
  "Frank's C++ Programming Style")
(c-add-style "FRANK" my-cpp-style)
(defun my-c-mode-common-hook ()
  (c-set-style "frank")
  (setq tab-width 4 ;; change this to taste, this is what K&R uses :)
        indent-tabs-mode nil ;; force only spaces for indentation
        c-basic-offset 4)
  ;; Turn on auto-newline
  (c-toggle-auto-newline 1)
  ;; Turn on subword minor mode
  (subword-mode))
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

-- Frank Dean - 17 Apr 2012

Related Topics: EmacsTips