20-CS-4003-001 Organization of Programming Languages Fall 2017
Macros

Lambda calculus, Type theory, Formal semantics, Program analysis

    Prev     Next     All lectures        Code

Macros in the C language

/* Macros are used quite frequently to make code 
   clearer and compact and to avoid function calls */

/* from: drivers/acpi/acpica/acmacros.h */
#define ACPI_MOVE_16_TO_64(d, s) \
   {(*(u64*)(void*)(d))=0; \
    ((u8*)(void*)(d))[6] = ((u8*)(void*)(s))[1]; \
    ((u8*)(void*)(d))[7] = ((u8*)(void*)(s))[0];}

void acpi_ps_get_next_simple_arg(
       struct acpi_parse_state *parser_state,
       u32 arg_type, 
       union acpi_parse_object *arg) {
   u8 *aml = parser_state->aml;
...
   ACPI_MOVE_16_TO_64(&arg->common.value.integer, aml);
...
}



/* from: include/linux/wait.h */
#define __WAIT_QUEUE_HEAD_INITIALIZER(name) {  \
   .lock    = __SPIN_LOCK_UNLOCKED(name.lock),  \
   .task_list  = { &(name).task_list, \
                   &(name).task_list } }

#define DECLARE_WAIT_QUEUE_HEAD(name) \
   wait_queue_head_t name = 
     __WAIT_QUEUE_HEAD_INITIALIZER(name)

DECLARE_WAIT_QUEUE_HEAD(short_queue);




/* from: include/linux/mutex.h */
#define __MUTEX_INITIALIZER(lockname) \
   { 
   .count = ATOMIC_INIT(1), \
   .wait_lock = \
      __SPIN_LOCK_UNLOCKED(lockname.wait_lock), \
   .wait_list = \
      LIST_HEAD_INIT(lockname.wait_list), \
      __DEBUG_MUTEX_INITIALIZER(lockname), \
      __DEP_MAP_MUTEX_INITIALIZER(lockname) }

#define DEFINE_MUTEX(mutexname) \
   struct mutex mutexname = \
      __MUTEX_INITIALIZER(mutexname)

static DEFINE_MUTEX(open_lock);
 -  Macros are textual substitutions that are used to avoid function calls and to present nicer looking code. To the left are some examples from the linux kernel.