Add -Werror=return-type
to CMakeLists.txt
#94
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
In C++ (but not C), when a return statement is omitted in a function that is supposed to return an
int
, it is undefined behaviour, even if the return value isn't being accessed by the caller. A warning is produced for this (-Wreturn-type
), but it's somewhat buried among the other warnings produced by the libraries in this repository (microbit-v2-samples).Here's an example:
Serial Output With Return Statements:
Serial Output Without Return Statements:
When the return statements are commented out, you get warnings such as the following:
And the program outputs:
It looks like it's "flowing off the end of the function" and running whatever is next in memory (in this case, instructions from the
main
function), which is supported by the fact that the behaviour can change when commenting out seemingly unrelated code.The misunderstanding comes from a belief that in non-void functions, failing to return is fine as long as the return value isn't used by the caller. This isn't the case however, and it's the kind of undefined behaviour that can lead to what we saw above. To add to the confusion, this article suggests this is only undefined behaviour in C++, and not in C which students are taught.
A different article goes into more detail.
Proposed Solution
This problem is symptomatic of a greater issue, which is the long list of warnings produced by the libraries in the
microbit-v2-samples
repo leading to people becoming "warning blind".To remediate just this specific issue however, we can change the warning to an error by adding
-Werror=return-type
toCMakeLists.txt
. This would stop compilation if there's no return statement in a function that should return a non-void value. More specifically (from the gcc warning options list):The repository still builds with
-Werror=return-type
, but adding it may cause someone else's code that depends on this repository to stop building with the new repository version.