Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warn if another typedef'd name of a type is used in an argument list

Tags:

c

gcc

Consider a large project, where many types are typedef'd, e.g.

typedef int age;
typedef int height;

and some functions getting arguments of those types:

void printPerson(age a, height h) {
    printf("Age %d, Height %d\n", a, h);
}

Is there a way to warn at compile time, if those arguments are of the wrong type, e.g.

age a = 30;
height h = 180;
printPerson(h, a); /* No warning, because a and h are both integers */

Does gcc (or some static code analysis tool) have an option to warn in such cases?

like image 961
urzeit Avatar asked Jun 19 '15 06:06

urzeit


3 Answers

There is no built-in support for this in GCC.

There is a feature request to add this, based on the Sparse nocast attribute. However, this hasn't been implemented. If you can use Sparse, though, you could do this by marking each typedef with __attribute__((nocast)).

In C++ you can do this by making wrapper classes rather than typedefs, and then simply not defining implicit conversions for them.

like image 189
Tom Tromey Avatar answered Oct 19 '22 21:10

Tom Tromey


Klocwork has some checks related to what they call "strong typing".

For your code it throws STRONG.TYPE.ASSIGN.ARG because argument types do not match.

It also complains about assigning int values (the consts) to age and height typed variables and about using the variables as int in printf.

I heard it is quite expensive, though.

like image 29
undur_gongor Avatar answered Oct 19 '22 22:10

undur_gongor


As has been made clear by the other responses, you're not going to get this for free from gcc. You are definitely into the world of static analysis tools to solve this.

There have been several suggestions for this, some of which require extra annotation, some of which don't but may be more than you're looking for. I therefore thought I'd throw one more into the mix...

A long stand by for me has been the various command line lint tools. In your case, I think PC-lint/flexelint fits very well even though it is a commercial tool. See here for its strong type checking.

like image 2
Peter Brittain Avatar answered Oct 19 '22 21:10

Peter Brittain