简体   繁体   中英

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

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)

eg

const int __declspec(deprecated) CLEAR_SOURCE = 0;
const int __declspec(deprecated("Use of this constant is deprecated. Use ClearFunc() instead. See: foobar.h"));

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM