?

Log in

No account? Create an account

Previous Entry | Next Entry

Printing the contents of a C macro

Have you ever wanted to expand a macro where the contents of a macro are converted into a string? If you have, here's a trick so you can!

Here's a common macro found in Burgerlib to align data.

#define BURGER_ALIGN(x,s) __align(s) (x)

There is no way to directly expand the macro to create a string of "__align(s) (x)" so this
line of code can not work properly.

printf("BURGER_ALIGN is defined as \"" BURGER_ALIGN(x,s) "\"\n");

However, there IS an indirect way of doing this. It requires the use of TWO separate macros so that
one converts the data into a NON macro string which then can be encapsulated with quotes
using a separate string.

Here is a working example.

// Generate a macro of interest

#define BURGER_ALIGN(x,s) __align(s) (x)

// This macro expands the contents of a macro into a string with quotes
#define BURGER_HASHMACRO(x) #x

// This macro expands the passed macro into x so it can't be double expanded
#define BURGER_MACRO_TO_STRING(x) BURGER_HASHMACRO(x)

printf("BURGER_ALIGN is defined as \"" BURGER_MACRO_TO_STRING(BURGER_ALIGN(x,s)) "\"\n");


The output will be 'BURGER_ALIGN is defined as "__declspec(align(s)) (x)"'

Simple, eh?

Tags: