0

In C++, I have some #define and also a count like this:

#define USE_1
#undef USE_2
#define USE_3

const size_t NUM_USE = (
        0
#ifdef USE_1
        + 1
#endif
#ifdef USE_2
        + 1
#endif
#ifdef USE_3
        + 1
#endif
        );

Now, I want to use it like this, which does not work as const variable cannot be used in a #if preprocessor statement:

#if NUM_USE > 0
// define here some specific code
#endif

One way to solve it would be to make some extra defines like this:

#ifdef USE_1 
#define HAVE_ANY_USE
#else
#ifdef USE_2
#define HAVE_ANY_USE
#else
#ifdef USE_3
#define HAVE_ANY_USE
#endif
#endif
#endif

#ifdef HAVE_ANY_USE
// define here some specific code
#endif

Is there a more elegant solution, maybe by using NUM_USE from above?

Ernie Mur
  • 481
  • 3
  • 18
  • What is the ultimate task that all of this is trying to accomplish? – Sam Varshavchik Sep 20 '22 at 00:30
  • I have code for a bigger project and want it to use for smaller projects where I want to exclude unneeded code and to save memory. It would be for an embedded device where the USE_1 etc. would be sensors (of course with a more descriptive name). The #define USE_ would be in a "device_specific_defines.h". – Ernie Mur Sep 20 '22 at 00:38
  • One reason is that if I define an array by using NUM_USE but NUM_USE would be zero, the compiler says that ISO C++ forbids arrays with size 0. – Ernie Mur Sep 20 '22 at 00:42
  • What does "I want to exclude unneeded code" mean? Try to pretend that a complete stranger walks off the street, and you're trying to explain this question to this stranger. What would you say to this stranger, so that this stranger immediately understands what question about C++, the programming language, is getting asked here? – Sam Varshavchik Sep 20 '22 at 00:49
  • "I want to exclude unneeded code" means that I want not have code compiled in which is not needed for the new project. I want to be able to set some #define in order a tailored executable is produced by using the same source code which is otherwise identical in most parts. – Ernie Mur Sep 20 '22 at 10:32

1 Answers1

2

You can define the USEs to be either 1 or 0 and then the sum can be a simple macro:

#define USE_1 1
#define USE_2 0
#define USE_3 1

#define NUM_USE (USE_1 + USE_2 + USE_3)
Daniel
  • 30,896
  • 18
  • 85
  • 139