Snippets‎ > ‎C++ Examples‎ > ‎

Hello World C++ Example compliant to Google C++ Style Guide with cpplint.py

BY MARKUS SPRUNCK


If you program you should always use a kind of minimal static analysis to avoid common errors. One popular style guide is the Google C++ Style Guide and Google published also a Python script to test some of the rules in the style guide. 

Preconditions

In Hello World C++ Example (for Cygwin) you find a description how to run the example code. To run the script cpplint.py you just need Python 2.7 installed.

Snippet #1 'Hello.cpp'

1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;

int main ()
{
    cout << "Hello World!";
    return 0;
}

Running the Python 2.7 script

1
python.exe cpplint.py hello.cpp

will create the following output:

1
2
3
4
5
6
7
8
9
hello.cpp:0:  No copyright message found.  You should have a line: "Copyright [year] <Copyright Owner>"  
                   [legal/copyright] [5]
hello.cpp:1:  Streams are highly discouraged.  [readability/streams] [3]
hello.cpp:2:  Do not use namespace using-directives.  Use using-declarations instead.  [build/namespaces] [5]
hello.cpp:4:  Extra space before ( in function call  [whitespace/parens] [4]
hello.cpp:5:  { should almost always be at the end of the previous line  [whitespace/braces] [4]
hello.cpp:8:  Could not find a newline character at the end of the file.  [whitespace/ending_newline] [5]
Done processing hello.cpp
Total errors found: 6

The Google C++ Style Guide recommends the use of streams only for logging and this is the major change in the sample code.

Snippet #2 'HelloOK.cpp'

1
2
3
4
5
6
7
8
9
/* Copyright 2012 XYZ */

#include <cstdio>

int main() {
    printf("Hello World!");
    return 0;
}


Running the Python 2.7 script

1
python.exe cpplint.py helloOk.cpp

will create the following output:

1
2
Done processing helloOK.cpp
Total errors found: 0