Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a preprocessor token to a string

I'm looking for a way to convert a preprocessor token to a string.

Specifically, I've somewhere got:

#define MAX_LEN 16 

and I want to use it to prevent buffer overrun:

char val[MAX_LEN+1]; // room for \0 sscanf(buf, "%"MAX_LEN"s", val); 

I'm open to other ways to accomplish the same thing, but standard library only.

like image 876
davenpcj Avatar asked Oct 27 '08 15:10

davenpcj


People also ask

How to stringify in C?

Stringification means turning a code fragment into a string constant whose contents are the text for the code fragment. For example, stringifying foo (z) results in "foo (z)". In the C preprocessor, stringification is an option available when macro arguments are substituted into the macro definition.

What is ## in preprocessor?

This is called token pasting or token concatenation. The ' ## ' preprocessing operator performs token pasting. When a macro is expanded, the two tokens on either side of each ' ## ' operator are combined into a single token, which then replaces the ' ## ' and the two original tokens in the macro expansion.

What does ## mean in macro?

The double-number-sign or token-pasting operator (##), which is sometimes called the merging or combining operator, is used in both object-like and function-like macros. It permits separate tokens to be joined into a single token, and therefore, can't be the first or last token in the macro definition.

What are preprocessing tokens?

Preprocessing tokens (pp-tokens) are a superset of regular tokens. Preprocessing tokens allow the source file to contain non-token character sequences that constitute valid preprocessing tokens during translation. There are four categories of preprocessing tokens: Header filenames, meant to be taken as a single token.


2 Answers

see http://www.decompile.com/cpp/faq/file_and_line_error_string.htm specifically:

#define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define AT __FILE__ ":" TOSTRING(__LINE__) 

so your problem can be solved by doing sscanf(buf, "%" TOSTRING(MAX_LEN) "s", val);

like image 126
Dan Avatar answered Oct 05 '22 05:10

Dan


I found an answer online.

#define VERSION_MAJOR 4 #define VERSION_MINOR 47  #define VERSION_STRING "v" #VERSION_MAJOR "." #VERSION_MINOR 

The above does not work but hopefully illustrates what I would like to do, i.e. make VERSION_STRING end up as "v4.47".

To generate the proper numeric form use something like

#define VERSION_MAJOR 4 #define VERSION_MINOR 47  #define STRINGIZE2(s) #s #define STRINGIZE(s) STRINGIZE2(s) #define VERSION_STRING "v" STRINGIZE(VERSION_MAJOR) \ "." STRINGIZE(VERSION_MINOR)  #include <stdio.h> int main() {     printf ("%s\n", VERSION_STRING);     return 0; } 
like image 45
davenpcj Avatar answered Oct 05 '22 07:10

davenpcj