Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate strings using preprocessor in C

How to concatenate two strings (one of them is stored in a variable) in C using preprocessors?

For example how to do this?

#define CONCAT(x,y) x y

//ecmd->argv[0] is equal to "sometext"
myfunc(CONCAT("/", ecmd->argv[0]), ecmd->argv[0]); //error: expected ')' before 'ecmd'
like image 212
SMUsamaShah Avatar asked Dec 29 '25 02:12

SMUsamaShah


1 Answers

You can't concatenate them using a macro like that. using the preprocessor, only raw strings (either string literals or names) can be concatenated.

You have to use strcat or some other technique to combine the strings. For example:

char * buf = malloc(strlen(ecmd->argv[0]) + 2);
buf[0] = '/'; buf[1] = '\0';
strcat(buf, ecmd->argv[0]);
like image 147
Foo Bah Avatar answered Dec 30 '25 16:12

Foo Bah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!