Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Visual C++: #pragma message

📅 2010-Sep-13 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ pragma, visual cpp ⬩ 📚 Archive

What if a programmer wants to draw attention to certain sections of code in certain source files? This could be for oneself or other team members. It could be certain work-in-progress, debugging or warning messages to watch out for. This could be for today or when one comes back to this code a long time later in the future.

One elegant and convenient way to achieve this is by using #pragma message. When the compiler finds a #pragma message, it outputs the message string to the Output window of Visual Studio. #pragma message strings can be left at the sections of code one wants to be signaled about. This way, even if a programmer comes back to some very old code, as soon as he compiles it the compiler signals him about certain information to watch out for in the code.

Using #pragma message is easy, like this:

// Foo.cpp
// ... Lots of Foo code ...

#pragma message( "HACK: Count of foo items updated! REMOVE later!" )
extern int debugCount;
++debugCount;

// ... Lots of Foo code ...

#pragma message can be tweaked to also output other information like the filename, line number and timestamp. Please see the MSDN article on #pragma message for more on that.

Note: The #pragma message output by the compiler can easily get lost in the Output window if the code produces lots of other warnings and errors. So, this is yet another reason why it is a good habit to make sure the code compiles with ZERO warnings and errors! ;-)


© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 @codeyarns@hachyderm.io📧