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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With