Reputation: 131445
If we write:
void foo() {
#warning "Danger Will Robinson!"
}
we'll get a warning when compiling foo()
. Now, What I want to do is for the compilation not to emit a warning, but for a warning to be emitted if foo()
is called.
Is that possible, using g++ and/or clang++?
Note: This question is somewhat similar to this one, about marking functions as "deprecated" (a-la C++14's [[deprecated]]
attribute). However, it's a different semantic. I do not want people to get the notion that my function is deprecated, but rather get a custom warning.
Upvotes: 3
Views: 1383
Reputation: 29955
C++11 added _Pragma
, which is like #pragma
but macros can expand to it. So, you can make a macro, that expands to this warning and the function:
#include <cstdio>
void foo() {
std::puts("foo is called!");
}
#define foo(...) _Pragma("message \"Danger Will Robinson!\"") \
foo(__VA_ARGS__)
int main() {
foo();
}
The main issue with this approach is that it will not respect overloads and warn on any function with the name foo
.
Upvotes: 4
Reputation: 131445
A suggestion from @StoryTeller in the comments, which works - partially - in GCC:
__attribute__ ((warning ("Danger Will Robinson!")))
void foo() { }
int bar() {
const int x = 123;
foo();
return x;
}
Why "partially"? As @StoryTeller says:
Dead code elimination can remove the warning should the call be on the eliminated branch
Have look at This GodBolt example: When you enable optimizations so that the function is inlined - the warning attribute is ignored.
Upvotes: 0