Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping a # symbol in a #define macro?

Without going into the gory details I want to use a #define macro that will expand to a #include but the '#' sign is confusing the preprocessor (as it thinks I want to quote an argument.)

For example, I want to do something like this:

#define MACRO(name) #include "name##foo" 

And use it thus:

MACRO(Test) 

Which will expand to:

#include "Testfoo" 

The humble # sign is causing the preprocessor to barf. MinGW gives me the following error:

'#' is not followed by a macro parameter

I guess I need to escape the # sign but I don't if this is even possible.

Yes, macros are indeed evil...

like image 326
Rob Avatar asked Jul 16 '09 06:07

Rob


People also ask

What does escaping a quote mean?

Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes: "Hello World." But what if my string had double quotes within it? "Hello "World.""

How do you escape special characters?

Escape CharactersUse the backslash character to escape a single character or symbol. Only the character immediately following the backslash is escaped. Note: If you use braces to escape an individual character within a word, the character is escaped, but the word is broken into three tokens.

What is escaping in shell?

Escaping is a method of quoting single characters. The escape (\) preceding a character tells the shell to interpret that character literally. With certain commands and utilities, such as echo and sed, escaping a character may have the opposite effect - it can toggle on a special meaning for that character.


2 Answers

It is possible to insert a hash token into the preprocessed token stream. You can do it as follows:

#define MACRO(hash, name) hash include name MACRO(#,"hello") 

—expands to:

# include "hello" 

However, the standard explicitly rules out any further analysis of such line for the existence of preprocessing directives [cpp.rescan]:

The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one.

like image 53
Yakov Galka Avatar answered Sep 28 '22 22:09

Yakov Galka


As far as I remember you cannot use another preprocessor directive in define.

like image 24
EFraim Avatar answered Sep 28 '22 22:09

EFraim