Last Updated: February 25, 2016
·
2.295K
· tkaretsos

Making multi-line C macros readable

I have been playing with some macro magic in C lately, so I ended up creating a really long multi-lined macro where I had to put '\' character at the end of every line. Pretty annoying, as the code was hard to read. It would be much better if the backslash was put at a fixed column in every line, let's say line 80 (pick whatever number suits you).

Here is a silly example of a multi-line macro:

#define AWESOME_MACRO(class_name, stored_type)\
\
struct class_name\
{\
  stored_type* data;\
};

I wanted to make the macro look like this:

#define AWESOME_MACRO(class_name, stored_type)                         \
                                                                       \
struct class_name                                                      \
{                                                                      \
  stored_type* data;                                                   \
};

Much, much more readable, especially if the macro is actually 200+ lines long. There are 2 ways, at least, to achieve this easily, powered by vim and awk. If you work with vim then enter visual line mode (V) and select the lines you wish to modify. Press colon and issue the following command:

s/\s*\\$/\=repeat(' ', 80-col('.')).'\'

If you do not use vim then awk is your friend. Open the terminal and type:

awk 'sub(/\\$/,"") { $0 = sprintf("%-79s\\",$0) } 1' file

To apply the changes in the file using awk:

awk 'sub(/\\$/,"") { $0 = sprintf("%-79s\\",$0) } 1' file > file.tmp && mv file.tmp file