3

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'
2
  • 1
    I think using macros is not the right way to do this. You'll end up inlining buffer allocation and string functions - you might as well use a function instead, which will be typesafe and debuggable. Commented Sep 28, 2011 at 11:31
  • I am already doing it with function, I am just curious to do this using preprocessors. Commented Sep 28, 2011 at 11:34

1 Answer 1

9

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

To elaborate: The pointer ecmd doesn't even exist when the preprocessor is running, nor does the memory it will later reference, so there cannot be any data that the preprocessor could access.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.