alexandernst
alexandernst

Reputation: 15099

How to #define in a macro (or alternatives)

I have this code:

#ifdef something32                           <----- might not be defined
    the_real_value = thing[something32];
    thing[something32] = my_value;
#else
    the_real_value = thing[something];   <------- guarantied to be defined (something)
    thing[something] = my_value;
#endif

#ifdef THE_OTHER_THING                       <--------- might not be defined
#ifdef something32
    thing32[something32] = my_value;
#else
    thing32[something] = my_value;
#endif
#endif

and I'll be using that a lot of times so I'd like to replace it with a macro. I know #ifdef's can't live insde a macro so I'm wondering how else I could replace all that code. Any ideas?

EDIT:

I'm sorry, I forgot to mention that something32 is just one of a pretty long list of variables.

The idea is to have something like

SHORTEN_MY_CODE(something, something32);
SHORTEN_MY_CODE(another_something, another_something32);
etc...

Upvotes: 2

Views: 163

Answers (2)

Mark Lakata
Mark Lakata

Reputation: 20907

If you are doing C++, I would consider just writing a function and declare it inline. If you have a full function, then you can put #ifdef inside the function.

If you post more of your code, I think we can offer more help. Misuse of the c-preprocessor is rampant. You probably don't want to use it the way you propose.

I don't understand how something,something32 and OTHER_THING get defined. Are they defined at the project level, or inside some header file?


Update: suggestion. However, you may want to read this first : access to the sys_call_table in kernel 2.6+

void* Hook(int f, void* hooked) {
#ifdef CONFIG_IA32_EMULATION
    void *old = ia32_sys_call_table[f];
    ia32_sys_call_table[f] = hooked;
#else
    void *old = sys_call_table[f];
    sys_call_table[f] = hooked;
#endif
    return old;
}


...

Hook(__NR_read, hooked_sys_read);
Hook(__NR_write, hooked_sys_write);

Upvotes: 0

Justin Meiners
Justin Meiners

Reputation: 11143

Turn your logic around and change what the macro is defined as based on condition - rather than defining a macro that contains a condition:

// define

#ifdef something32
    #define SOMETHING_VAR something32
#else
    #define SOMETHING_VAR something

#define SHORTEN_MY_CODE the_real_value = thing[SOMETHING_VAR]; \
    thing[SOMETHING_VAR] = my_value;

#ifdef THE_OTHER_THING
     #define SHORT_OTHER() thing32[SOMETHING_VAR] = my_value
#else
     #define SHORT_OTHER() 
#endif

// usage
SHORTEN_MY_CODE()
SHORT_OTHER()

ORIGINAL ANSWER

#ifdef something32
    #define MY_MACRO the_real_value = thing[something32]; \
    thing[something32] = my_value; 
#else
    #define MY_MACRO the_real_value = thing[something]; \
    thing[something] = my_value;
#endif

Upvotes: 2

Related Questions