4

Is it possible to put variable text_info to readline among with colors?
GCC debuger gives me this error: " error: expected ‘)’ before 'text'

#include <readline/readline.h>

#define CYELLOW "\001\e[0;31m\002"
#define RESET   "\001\e[0m\002"

int main(int argc, char **argv)
{
    char *text_info = "its very simple string";
    readline(CYELLOW text_info RESET);
    return 0;
}

I know that the way below works but it's not the case.

int main(int argc, char **argv)
{
    readline(CYELLOW "simple string" RESET);
    return 0;
}
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
test
  • 401
  • 1
  • 5
  • 15

2 Answers2

1

The line you posted doesn't work because it can't be combined during build time:

readline(CYELLOW text_info RESET);

As @Weaterh Vane has already metioned in the comment above, the only real solution is to build the string during runtime via sprintf or better snprintf.

 char aBuffer[100];
 snprintf(aBuffer, sizeof(aBuffer), "%s%s%s", CYELLOW, text_info, RESET);

Edit: Please keep in mind, that aBuffer in the above example may be to small (depending on the length of text_info). Depending on your application you can just increase the size of 100 or dynamically allocating the buffer.

Benjamin J.
  • 1,239
  • 1
  • 15
  • 28
1

In the working code, this line

readline(CYELLOW text_info RESET);

is macro-expanded to

readline("\001\e[0;31m\002" "simple string" "\001\e[0m\002");

which in turn, after string literal combination ends up as

readline("\001\e[0;31m\002simple string\001\e[0m\002");

which contains a simple string literal. No operators are involved, but it still ends up as a single parameter to the function.

In contrast to that, this line

readline(CYELLOW text_info RESET);

is macro-expanded to

readline("\001\e[0;31m\002" text_info "\001\e[0m\002");

which is not subject to string literal combination and therefor ends up with three string expressions (i.e. not exclusively literal strings, one being a non-literal string, a pointer to chars) without any operator in between.

Also, there is no simple operator for string concatenation (cases outside of string literal combination).

So in order to give a single string parameter ("string" as in "C-compatible zero-terminated sequence of chars, maybe array), you will have to construct such a string and then use it as single parameter for the function.

As Weather Vane has proposed, sprintf() is probably the tool to do that.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54