C++ resources
- Google Coding Style: reference and explanations on various C++ coding style decisions.
- Bjarne Stroustrup's C++ Style and Technique FAQ: interesting (and technical) questions answered by C++ creator.
Coding Style
This document is based on http://techbase.kde.org/Policies/Kdelibs_Coding_Style with small changes and additions.
Indentation
- No tabs
- 4 Spaces instead of one tab
Includes
- Three groups of include statements:
- Its own header (for CPP files)
- System libraries
- Other headers
- One blank line between each group
Example:
// right (in qzionabstractcanvas.cpp) #include "qzionabstractcanvas.h" #include <QDebug> #include <QRegion> #include <QPainter> #include <QPaintEvent> #include "qzionobject.h"
Modifiers
Your class definition should start with its public: section, followed by its protected: section and then its private: section.
If any of these sections are empty, omit them.
Within each section, the declarations generally should be in the following order:
- Typedefs and Enums
- Constants
- Constructors
- Destructor
- Methods, including static methods
- Data Members, including static data members
Variable declaration
- Each variable declaration on a new line
- Each new word in a variable name starts with a capital letter (camelCase)
- Avoid abbreviations
- Take useful names. No short names, except:
- Single character variable names can denote counters and temporary variables whose purpose is obvious.
- Variables and functions start with a small letter.
Example:
// wrong KProgressBar *prbar; QString prtxt, errstr; // correct KProgressBar *downloadProgressBar; QString progressText; QString errorString;
Whitespace
- Use blank lines to group statements
- Use only one empty line
- Use one space after each keyword
- For pointers or references, use a single space before '*' or '&', but not after
- No space after a cast
- Use space between operators
- Use space after comma
Example:
// wrong
QString* myString;
if(true){
}
// correct
QString *myString;
if (true) {
}
Braces
As a base rule, the left curly brace goes on the same line as the start of the statement.
Example:
// wrong
if (true)
{
}
// correct
if (true) {
}
Exception: Function implementations, class, struct and namespace declarations always have the opening brace on the start of a line.
Example:
void debug(int i)
{
qDebug("foo: %i", i);
}
class Debug
{
};
You may omit the curly braces when the body of a conditional statement contains only one line.
Example:
// correct
if (true)
return true;
for (int i = 0; i < 10; ++i)
qDebug("%i", i);
Switch statements
Case labels are on the same column as the switch
Example:
switch (myEnum) {
case Value1:
doSomething();
break;
case Value2:
doSomethingElse();
// fall through
default:
defaultHandling();
break;
}
Line breaks
- Try to keep lines shorter than 80 characters, inserting line breaks as necessary.
- Use line breaks at column 80 also for function declaration (parameters line breaks align with the first parameter).
- The ':' in constructors implementations have a line break with 4 spaces and the next line breaks at 80 characters
Misc
- Use this only when necessary (e.g. to resolve name conflicts)
- Name convention: getter is value() and setter is setValue()
- Private/protected variables should start with underscore
- Declare variables in the smaller scope possible and as close to the use as possible
Tools
Vim script
You can find a vim script in kdesdk/scripts/kde-devel-vim.vim that helps you to keep the coding style correct. In addition to defaulting to the kdelibs coding style it will automatically use the correct style for Solid and kdepim code. If you want to add rules for other projects feel free to add them in the SetCodingStyle? function.
To use the script, include it in your {{path|~/.vimrc}} like this:
source /path/to/kde/sources/kdesdk/scripts/kde-devel-vim.vim
Emacs
;; Qt Style
(c-add-style
"qt"
'("stroustrup"
(indent-tabs-mode . nil)
(tab-width . 4)))
(add-hook 'c++-mode-hook
(lambda ()
(if (string-match
(regexp-opt '("/qzion" "/qedje" "/qt"))
(buffer-file-name))
(c-set-style "qt"))))
(add-to-list 'auto-mode-alist '("\\.h\\'" . c++-mode))
To highlight tabs with red:
(defface extra-whitespace-face
'((t (:background "red")))
"Used for tabs and such.")
(defvar my-extra-keywords
'(("\t" . 'extra-whitespace-face)))
(add-hook 'c++-mode-hook
(lambda ()
(font-lock-add-keywords nil my-extra-keywords)))
using astyle:
(defvar astyle-command "astyle --indent=spaces=4 --brackets=linux --indent-labels --pad=oper --unpad=paren --one-line=keep-statements --convert-tabs --indent-preprocessor")
(defun astyle-region (start end)
"Run astyle on region, formatting it in a pleasant way."
(interactive "r")
(save-excursion
(shell-command-on-region start end astyle-command nil t)
)
)
(defun astyle-buffer ()
"Run astyle on whole buffer, formatting it in a pleasant way."
(interactive)
(save-excursion
(astyle-region (point-min) (point-max))))
(add-hook 'c-mode-common-hook
'(lambda ()
(define-key c-mode-map "\C-cr" 'astyle-region)
(define-key c-mode-map "\C-cb" 'astyle-buffer)
(define-key c++-mode-map "\C-cr" 'astyle-region)
(define-key c++-mode-map "\C-cb" 'astyle-buffer)))
Comments
Comments for class and functions are extremely necessary.
All comments must follow doxygen Qt style (Doxygen manual: http://www.stack.nl/~dimitri/doxygen/manual.html):
- 4 spaces of indentation
- The beginning and the end of the comment tags in separated lines
//wrong
/*! text ...
*/
// correct
/*!
text ...
*/
All class comments must have at least this minimum set:
/*!
\class Test
\brief A test class.
A more detailed class description.
*/
Function comments must be placed near the function body, avoid using \fn.
/*!
text ...
*/
void Test::func()
{
}
Whenever is possible try to link common functions with \sa (see also):
/*!
Sets object position...
\sa pos()
*/
void Test::setPos(const int x, const int y)
{
}
When the functions are in the same class use short signature of the function (e.g. \sa pos() instead of \sa Test::pos())
