12

I often come across keywords or one-word identifiers defined with another name. For example, boost defines noexcept as BOOST_NOEXCEPT, some C++ standard libraries replace [[nodiscard]] with _NODISCARD, Windows API is prone to introduce their own macros as well, and so forth. I didn't really manage to find anything which would explain this.

This makes an unfamiliar person search for what such macros mean which therefore makes the code a bit harder to understand (at least this is how I see it). Why is such tendency so widespread? What is the purpose of replacing existing one-word constructs with macros?

Boann
  • 48,794
  • 16
  • 117
  • 146
Kaiyakha
  • 1,463
  • 1
  • 6
  • 19
  • I guess it's for flexibility in a codebase which has to run on a variety of different compilers (there's often a `config.h` file to define all these macros for any particular compiler). An IDE with a 'Jump to Definition' feature is a big help in cases like this. – Paul Sanders Oct 15 '22 at 10:34
  • 2
    Some code has to work across many different standards and many different compilers that don't agree on how to do particular things. Using macros that can be defined or not is a way to manage that. – Retired Ninja Oct 15 '22 at 10:35
  • 2
    *"This makes an unfamiliar person search for what such macros mean"*. It shouldn't, these macros are for internal use by the library. You shouldn't use them and it shouldn't matter what these macros expand to. – François Andrieux Oct 15 '22 at 11:07
  • 2
    @FrançoisAndrieux In the case of the WIN32 API, you do have to get to grips with (some of) them, unfortunately. – Paul Sanders Oct 15 '22 at 11:25

2 Answers2

16

The most useful case of these is when you target both compilers that support a new feature and ones that do not.
For instance:

#if CompilerSupportsNoexcept
#define NOEXCEPT noexcept
#else
#define NOEXCEPT
#endif
Daniel
  • 30,896
  • 18
  • 85
  • 139
  • Also worth mention that for language versions that predates ones which introduced a particular feature there is often a compiler extention which does that. Unique for each compiler. – Revolver_Ocelot Oct 15 '22 at 10:36
6

This may be used in different scenarios for flexibility and code clarity. Following cases come in mind:

  • support for different compilers, which implements the same feature in a different way or do not support at all
  • support for different build options, i.e. building static vs dynamic library
  • support for different OSes (functions, exported by dynamic libraries, in Windows and Linux would have different signatures)
  • Debug vs Release builds
Nickolay Olshevsky
  • 13,706
  • 1
  • 34
  • 48