From RidgeRun Developer Connection
C++
Tools Considered
- g++
- The plain compiler invoked as
g++ -Weverything -c
on the file. Not ideal nor a real linter, but mainly for convenience.
- clang++
- The plain compiler invoked as
clang++ -Weverything -c
on the file. Not ideal nor a real linter, but mainly for convenience.
- cppcheck
- A C/C++ linter with a novel flow sensitive analysis.
- cpplint
- A linter built by google specifically for their coding standard.
- clang-tidy
- A clang-based C++ linter
- clang-analyzer
- Another clang-based static C++ linter with awesome reporting features.
Checks
64 Bit Compatibility
// return cast from ptr to int
int ptr_to_int()
{
void * p = 0;
return p;
}
// return cast from ptr to long
long ptr_to_long()
{
void * p = 0;
return p;
}
// return cast from int to ptr
void * int_to_ptr()
{
int i = 0;
return i;
}
// return cast from long to ptr
void * long_to_ptr()
{
long l = 0;
return l;
}
int main ()
{
void * p = 0;
// assign address to int
int i = p;
// assign address to long
long l = p;
//assign int to address
p = i;
//assign long to address
p = l;
return 0;
}
Assert
#include <assert.h>
volatile static int i = 0;
bool side_effect ()
{
i++;
return true;
}
int main ()
{
// Indirect assignment via preincrement
assert (++i);
// Indirect assignment via postincrement
assert (i++);
// Direct assignment in assert
assert (i = 1);
// Assert calling function with side effects
assert (side_effect());
return 0;
}
Linter |
preinc |
postinc |
assignment |
function
|
g++ -Weverything |
N |
N |
N |
N
|
clang++ -Weverything |
N |
N |
N |
N
|
cppcheck[1] |
N[2] |
Y |
Y |
Y
|
cpplint |
N |
N |
N |
N
|
clang-tidy |
N |
N |
N |
N
|
clang-analyze |
N |
N |
N |
N
|
Memory Leaks (function variables)
#include <glib.h>
#include <stdlib.h>
int main ()
{
// New
int *a = new int;
// Malloc
int *b = (int *)malloc(sizeof (int));
// Calloc
int *c = (int *)calloc(1, sizeof (int));
// Realloc
int *d = (int *)realloc(0, sizeof (int));
// External library
int *e = (int *)g_malloc(sizeof (int));
return 0;
}
Linter |
New |
Malloc |
Calloc |
Realloc
|
g++ -Weverything |
N |
N |
N |
N
|
clang++ -Weverything |
N |
N |
N |
N
|
cppcheck |
Y |
Y |
Y |
Y
|
cpplint |
N |
N |
N |
N
|
clang-tidy |
Y |
Y |
Y |
Y
|
clang-analyze |
Y |
Y |
Y |
Y
|