Add my own compiler warning

Viewed 34322

When using sprintf, the compiler warns me that the function is deprecated.

How can I show my own compiler warning?

6 Answers

In Visual Studio,

#pragma message ("Warning goes here")

On a side note, if you want to suppress such warnings, find the compiler warning ID (for the deprecated warning, it's C4996) and insert this line:

#pragma warning( disable : 4996)

Although there is no standard #warning directice, many compilers (including GCC, VC, Intels and Apples), support #warning message.

#warning "this is deprecated"

Often it is better to not only bring up a warning (which people can overlook), but to let compiling fail completely, using the #error directive (which is standard):

#if !defined(FOO) && !defined(BAR)
#  error "you have neither foo nor bar set up"
#endif

The answer from noelicus is great, but I had to use round brackets for the line number instead of square brackets.

This means their code

// with line number  
#define STRING2(x) #x  
#define STRING(x) STRING2(x)  

#pragma message (__FILE__ "[" STRING(__LINE__) "]: test")

should be

// with line number  
#define STRING2(x) #x  
#define STRING(x) STRING2(x)  

#pragma message (__FILE__ "(" STRING(__LINE__) "): test")

With a message which is actually interpreted by the compiler as a warning:

#define STRING2(x) #x  
#define STRING(x) STRING2(x)  
#pragma message(__FILE__ "(" STRING(__LINE__) "): warning: My own compiler warning, which can be double-clicked to go to the source code line.")

I'm using Visual Studio 2022 with compiling VS2017 projects, if this makes a difference.

Related