phandinhlan
phandinhlan

Reputation: 583

Preventing Undefined Macro

In C and C++, when using a macro like so:

#if ( 1 == __MY_MACRO__ )
// Some code
#endif

The compiler will not catch if MY_MACRO is not defined and will consider it 0. This could cause a lot of hidden bugs when the design of the code is intended such that the macro must be defined (non-zero).

Is there away to get to compiler to report this, even if the compiler natively doesn't look for such thing?

Upvotes: 2

Views: 4185

Answers (6)

Petr
Petr

Reputation: 83

If the macro is used as compile switch try this way.
in a configuration file:

#define FEATURE_1_ENABLED() (1)
#define FEATURE_2_ENABLED() (0)

in place you checking the value:

#if FEATURE_1_ENABLED()
// whatever
#endif

in contrast to your example this does show error when macro is not visible by mistake (at least in my ide)

Upvotes: 0

phandinhlan
phandinhlan

Reputation: 583

Someone I know came up with a clever 1 liner

#if ( (1/defined(_MY_MACRO__) && 1 == _MY_MACRO__ ) )
//code
#endif

If _MY_MACRO__ is not defined, it will cause divide by zero error.

Upvotes: 0

mantal
mantal

Reputation: 1209

You can use #ifdef or ifndef to check if a macro is defined of not.

Example :

#ifndef MY_MACRO
# error "MY_MACRO is not defined"
#endif

More informations can be found here : https://gcc.gnu.org/onlinedocs/cpp/Ifdef.html

Upvotes: 3

BLUEPIXY
BLUEPIXY

Reputation: 40155

#ifndef __MY_MACRO__
  #error "MY_MACRO NOT DEFINED"
#endif

Upvotes: 6

phandinhlan
phandinhlan

Reputation: 583

I have to resort to

#if !defined( __MY_MACRO__ )
MACRO_NOT_DEFINED;  //to cause compiler error
#endif
#if ( 1 == __MY_MACRO__ )
//code
#endif

Which looks rather ugly.

Upvotes: 0

AAT
AAT

Reputation: 3386

Use #if defined(__MY_MACRO__) to test if the macro value is defined.

Upvotes: 7

Related Questions