Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make compilation stop nicely if a constant is used in my source file?

Tags:

c++

visual-c++

I want to test for the use of a constant in a source file and if it is used, stop compilation.

The constant in question is defined in a generic driver file which a number of driver implementations inherit from. However, it's use has been deprecated so subsequent updates to each drivers should switch to using a new method call and not the use of this const value.

This doesn't work obviously

#ifdef CONST_VAR
#error "custom message"
#endif

How can I do this elegantly? As It's an int, I can define CONST_VAR as a string and let it fail, but that might make it difficult for developers to understand what actually went wrong. I was hoping for a nice #error type message.

Any suggestions?


The Poison answer here is excellent. However for older versions of VC++ which don't support [[deprecated]] I found the following works.

Use [[deprecated]] (C++14 compilers) or __declspec(deprecated)

To treat this warning as an error in a compilation unit, put the following pragma near the top of the source file.

#pragma warning(error: 4996)

e.g.

const int __declspec(deprecated) CLEAR_SOURCE = 0;
const int __declspec(deprecated("Use of this constant is deprecated. Use ClearFunc() instead. See: foobar.h"));
like image 405
hookenz Avatar asked Jun 23 '19 22:06

hookenz


1 Answers

AFAIK, there's no standard way to do this, but gcc and clang's preprocessors have #pragma poison which allows you to do just that -- you declare certain preprocessor tokens (identifiers, macros) as poisoned and if they're encountered while preprocessing, compilation aborts.

#define foo
#pragma GCC poison printf sprintf fprintf foo
int main()
{
  sprintf(some_string, "hello"); //aborts compilation
  foo; //ditto
}

For warnings/errors after preprocessing, you can use C++14's [[deprecated]] attribute, whose warnings you can turn into errors with clang/gcc's -Werror=deprecated-declarations .

int foo [[deprecated]];
[[deprecated]] int bar ();

int main()
{
    return bar()+foo;
}

This second approach obviously won't work for on preprocessor macros.

like image 119
PSkocik Avatar answered Oct 29 '22 11:10

PSkocik