Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessor check if multiple defines are not defined

I have a selection of #defines in a header that are user editable and so I subsequently wish to check that the defines exist in case a user deletes them altogether, e.g.

#if defined MANUF && defined SERIAL && defined MODEL     // All defined OK so do nothing #else     #error "User is stoopid!" #endif 

This works perfectly OK, I am wondering however if there is a better way to check if multiple defines are NOT in place... i.e. something like:

#ifn defined MANUF || defined SERIAL ||.... // note the n in #ifn 

or maybe

#if !defined MANUF || !defined SERIAL ||.... 

to remove the need for the empty #if section.

like image 606
Toby Avatar asked Jun 21 '13 14:06

Toby


People also ask

What does# ifndef mean in C?

In the C Programming Language, the #ifndef directive allows for conditional compilation. The preprocessor determines if the provided macro does not exist before including the subsequent code in the compilation process.

What does# ifdef mean in c++?

The meaning of #ifdef is that the code inside the block will be included in the compilation only if the mentioned preprocessor macro is defined. Similarily #if means that the block will be included only if the expression evaluates to true (when replacing undefined macros that appears in the expression with 0).

What is ifndef and ifdef?

The #ifndef directive checks for the opposite of the condition checked by #ifdef . If the identifier hasn't been defined, or if its definition has been removed with #undef , the condition is true (nonzero). Otherwise, the condition is false (0).

How# ifdef works in C?

The #ifdef is one of the widely used directives in C. It allows conditional compilations. During the compilation process, the preprocessor is supposed to determine if any provided macros exist before we include any subsequent code.


2 Answers

#if !defined(MANUF) || !defined(SERIAL) || !defined(MODEL) 
like image 184
Sergey L. Avatar answered Sep 25 '22 02:09

Sergey L.


FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.

main.c has a main wrapper like this:

#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB) int main(int argc, char *argv[]) {   // the true main() routine. } 

spi.c, serial.c and usb.c have main wrappers for their respective test code like this:

#ifdef TEST_USB int main(int argc, char *argv[]) {   // the  main() routine for testing the usb code. } 

config.h Which is included by all the c files has an entry like this:

// Uncomment below to test the serial //#define TEST_SERIAL   // Uncomment below to test the spi code //#define TEST_SPI  // Uncomment below to test the usb code #define TEST_USB 
like image 38
netskink Avatar answered Sep 25 '22 02:09

netskink