The formatting rules for GCC are described in http://gcc.gnu.org/contribute.html and in http://gcc.gnu.org/codingconventions.html.

There is a script that detects some errors (contrib/check_GNU_style.sh), however it misses many errors, specially wrong indentation.

If you use Emacs, you can use M-x c-set-style and type 'gnu' for the style. And also, you can configure like this in your ~/.emacs file:

;; This line is not actually needed, it is on by default.
(setq-default indent-tabs-mode t)

(add-hook 'c-mode-hook 'linux-c-mode)
(defun linux-c-mode()
;; set gnu style.
 (c-set-style "gnu")
;; TAB offset set to 2
 (setq c-basic-offset 2)
 )

Alternatively, on Emacs 23.1 or later, you can use directory-specific variables. Create a file .dir-locals.el in some directory between root and GCC sources with following contents:

((c-mode . ((c-file-style . "GNU")
            (c-basic-offset . 2)
            (indent-tabs-mode t))))

If you use Vim, you can use the following settings:

$ cat ~/.vim/after/ftplugin/c.vim
GNU Coding Standards
setlocal cindent
setlocal cinoptions=>4,n-2,{2,^-2,:2,=2,g0,h2,p5,t0,+2,(0,u0,w1,m1
setlocal shiftwidth=2
setlocal softtabstop=2
setlocal textwidth=79
setlocal fo-=ro fo+=cql

If you use vscode, you can use the following settings:

{
    "editor.rulers": [
        80, 1000
    ],
    "editor.renderWhitespace": "boundary",
    "editor.tabSize": 8,
    "files.associations": {
        "*.pd": "c",
        "*.md": "c",
        "*.def": "c"
    },

    "editor.guides.indentation": true,
    "editor.insertSpaces": false,
    "editor.detectIndentation": false,
    "editor.bracketPairColorization.independentColorPoolPerBracketType": true
}

Editor Config

Several editors support the https://EditorConfig.org specification. That allows you to put a .editorconfig file in your GCC source tree and your editor will use the desired config. You can add the .editorconfig file to the .git/info/exclude file so that Git ignores it. At the time of writing (2022) EditorConfig cannot be used for correctly indenting curly braces, but can be used to correctly select TABs vs spaces and other whitespace conventions. The following is an example .editorconfig file:

root = true

[*.cc]
indent_style = tab
indent_size = 2
tab_width = 8
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[Makefile*,ChangeLog*]
indent_style = tab
indent_size = 8
trim_trailing_whitespace = true

[*.py]
indent_style = space
indent_size = 4
trim_trailing_whitespace = true

Libstdc++ Formatting

Libstdc++ uses different conventions for C++ formatting from the rest of GCC. https://github.com/mattkretz/vim-gnuindent is a Vim plugin implementing the libstdc++ conventions.

None: FormattingCodeForGCC (last edited 2024-07-31 16:58:13 by TamarChristina)