Buffer Yard
Language setup

Emacs C Setup: clangd, Builds and Debugging with GDB

Updated

clangd starts, Eglot reports it is connected, and then every #include "config.h" lights up as an error. Nothing is wrong with Emacs, and nothing is wrong with clangd. It simply does not know which include paths, defines and standard your build uses, and C has no project file that would tell it. Fixing that is the first real step of a C setup, so this page starts there and adds the mode afterwards.

Give clangd a compilation database

clangd reads a file called compile_commands.json: a JSON list with one entry per source file, containing the exact compiler command used to build it. With that file in the project root (or in a build/ directory, which clangd also checks), it sees the same flags the compiler does.

How you produce it depends on the build system.

CMake writes it for you with one flag:

cmake -S . -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
ln -s build/compile_commands.json .

The symlink is optional when the build directory is called build, but it removes any doubt.

Make, or anything else that calls the compiler directly, goes through Bear, which intercepts compiler invocations during a build and records them:

make clean
bear -- make

The make clean matters. Bear only records commands that actually run, so an up-to-date tree produces an empty or partial database.

Meson generates the file in its build directory by default. For a tiny project with no build system at all, a compile_flags.txt with one flag per line (-Iinclude, -std=c17) is enough for clangd.

c-ts-mode and Eglot

Emacs 29.1 added c-ts-mode, a tree-sitter mode for C. Install the grammar once with M-x treesit-install-language-grammar RET c, then remap the classic mode so every .c and .h file uses it:

(add-to-list 'major-mode-remap-alist '(c-mode . c-ts-mode))

(use-package eglot
  :hook (c-ts-mode . eglot-ensure)
  :config
  (add-to-list 'eglot-server-programs
               '((c-ts-mode c-mode) . ("clangd" "--header-insertion=never"))))

(setq c-ts-mode-indent-offset 4
      c-ts-mode-indent-style 'linux)

Eglot would find clangd without the explicit entry. The entry is there for the flag: by default clangd inserts #include lines when you accept a completion for a symbol from an unincluded header, which is helpful in some codebases and wrong in many C projects with their own include conventions.

The older c-mode from CC Mode is still there and still excellent at indentation, with styles like gnu, k&r, linux and bsd. If a project relies on a CC Mode style through .dir-locals.el, leave the remap out for that project. c-ts-mode supports a smaller set of styles, though gnu, k&r, linux and bsd are among them.

With clangd connected you get diagnostics through Flymake, completion through completion-at-point (shown by whatever front end the completion guide set up), M-. to jump to definitions, and M-x eglot-rename that renames across files correctly because clangd understands scope.

Building with M-x compile

Emacs has had a compile loop since long before language servers. M-x compile asks for a command (default make -k), runs it in a *compilation* buffer and turns every file:line:col: error into a link. M-g n and M-g p step through errors while you stay in the source buffer.

M-x recompile reruns the last command without asking. Inside the compilation buffer, g does the same. Bind recompile to a key you can hit without thinking; a function key works well, because you will press it hundreds of times a day.

Set the command per project instead of retyping it:

;; .dir-locals.el in the project root
((nil . ((compile-command . "cmake --build build -j8"))))

Two variables make the loop nicer. (setq compilation-scroll-output 'first-error) keeps the buffer scrolling until the first error appears, then stops there. (setq compilation-ask-about-save nil) saves modified buffers before compiling without asking.

Debugging with GDB

M-x gdb starts GDB through Emacs’s GUD interface. Emacs fills in gdb -i=mi followed by your program; keep the -i=mi part, because the multi-window interface depends on the machine interface protocol. Compile with -g and without heavy optimisation first, or variables will show as optimised out.

On its own, M-x gdb gives you a GDB console and a source buffer with an arrow at the current line. Set gdb-many-windows and it lays out the full IDE arrangement: console, source, local variables, stack, breakpoints and I/O for the program’s output.

(setq gdb-many-windows t
      gdb-show-main t)

In the source buffer, C-x C-a C-b sets a breakpoint on the current line, and the left fringe lets you click to toggle them. gud-next, gud-step and gud-cont correspond to GDB’s next, step and continue. Most people bind the three to function keys after a day of typing them.

On Linux this works out of the box. On macOS GDB itself is the problem, as the FAQ explains.

clang-format

clangd formats code through Eglot using the nearest .clang-format file, so M-x eglot-format-buffer (or eglot-format on a region) is all you need. Format only on save for projects that already have a .clang-format; reformatting a file in a project without one produces diffs in lines you never touched, and maintainers notice.

(add-hook 'c-ts-mode-hook
          (lambda ()
            (when (locate-dominating-file default-directory ".clang-format")
              (add-hook 'before-save-hook #'eglot-format-buffer nil t))))

The clang-format package on MELPA does the same without a server, with clang-format-buffer and clang-format-region.

Elsewhere on Buffer Yard

The Rust page uses the same compile and recompile loop with Cargo, which makes the two configs easy to keep side by side. For debugging beyond GDB, including LLDB through DAP adapters, dape on GNU ELPA is the package to look at; general package choices are on the packages guide. C++ uses this same setup with c++-ts-mode added to the hooks; the languages index lists the rest.

Header files are worth one last check in mixed codebases: a .h file opens in a C mode by default. Emacs 29 also ships c-or-c++-ts-mode, which looks at the file’s contents and picks the C or C++ mode, so adding ("\\.h\\'" . c-or-c++-ts-mode) to auto-mode-alist saves you from C++ headers highlighted as C.

Questions readers ask

Why does clangd report missing headers that compile fine?

clangd does not know your compiler flags until it reads a compile_commands.json. Generate one with CMake or Bear, place it (or a symlink) in the project root, then run M-x eglot-reconnect.

Should I use c-mode or c-ts-mode?

On Emacs 29 or later with the C grammar installed, c-ts-mode gives more accurate highlighting and is simpler to configure. c-mode, part of CC Mode, is still the better fit if you depend on its many indentation styles or on packages written for it.

Can I debug with GDB inside Emacs on macOS?

The Emacs side works, but getting GDB itself to run on recent macOS needs code signing and is fragile. Most macOS users run LLDB instead, either in a terminal or through a DAP client such as dape.