user1196549
user1196549

Reputation:

Multiline code replication with the C preprocessor

I want to replicate some code snippets using the C preprocessor. I know how to handle multi-line macros, but I am facing two difficulties:

  1. I didn't find a way to embed comments in the macro,

  2. The generated output doesn't have newlines.

E.g. here is what I would like to be able to do

#define Snippet \
// This is my snippet \
a= b + c;

(sort of).

Desired generated output:

// This is my snippet
a= b + c;

Do you have solutions for 1. and 2. ? Thanks in advance.

Upvotes: 0

Views: 206

Answers (2)

user1196549
user1196549

Reputation:

For those interested, I have solved as follows:

  1. The following macro allows to embed C++-style comments:

    #define Comment(Text) #/#/ Text
    
  2. I am adding a reserved character before the end of every line. After macro expansion, I turn it to a newline with a find/replace macro.

    #define Snippet \
    Comment(This is my snippet)@\
    a= b + c;
    

expands as

// This is my snippet@a= b + c;

and after substitution

// This is my snippet
a= b + c;

I am still looking for a way to have a symbol that would expand as a newline, though the current solution is already manageable.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

The problem with the macro as you show it is because of how the compilation process works.

If you look at e.g. this C translation phase reference you will see that line-continuation happens in phase 2, then comments are replaced by space in phase 3, and finally preprocessing happens in phase 4.

That is, after phase 2 what you have is

#define Snippet // This is my snippet a= b+c;

Then after replacing comments in phase 3 the macro definition becomes empty.

The solution for comments is to use block comments using /* and */.

There is no solution for the line-continuation problem, as that's how it must work.

Upvotes: 1

Related Questions