Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger a warning when a certain function is called (not compiled)?

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.

like image 372
einpoklum Avatar asked Apr 14 '26 00:04

einpoklum


1 Answers

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.

like image 155
Ayxan Haqverdili Avatar answered Apr 16 '26 14:04

Ayxan Haqverdili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!