2

I was wondering if anyone has come up with a clever macro that would change the console print colour based on which source file has called printf.

The best way I've been able to figure out how to do this is.

//print.h
#define PRINT_NORMAL         printf("\033[0m");
#define PRINTF(style, ...)   printf(style); printf(__VA_ARGS__); PRINT_NORMAL

//myfile.h
#define MYFILE_STYLE "\033[1;34m"

//myfile.c
...
PRINTF(MYFILE_STYLE, "Something with myfile style");
...

I was wondering if there is some sneaky way I could define PRINTF so that it wouldn't need the style parameter, essentially grabbing a local variable to use as the style.

EDIT:

It kind of came to me immediately after writing the last sentence.

I should be able to define a local style variable in each of my .c files and change my macro to

#define PRINTF(...)   printf(style); printf(__VA_ARGS__); PRINT_NORMAL

The next question: Is there a better way to combine those 3 printf statements?

user3817250
  • 1,003
  • 4
  • 14
  • 27
  • 1
    As to your last question: You can wrap several statements in a `do { ... } while (0)` loop, which lets you use the macro in the same way as you would use a function, see [here](http://stackoverflow.com/questions/154136/do-while-and-if-else-statements-in-c-c-macros). – M Oehm Sep 09 '14 at 14:44

1 Answers1

1

Create a function calculateStyle() in your (new) print.c module which calculates a hash from the filename, then selects a color based on this hash, and returns the style command.

Then your PRINTF() macro will become:

#define PRINTF(...) printf(calculateStyle(__FILE__)); printf(__VA_ARGS__); PRINT_NORMAL

Of course you can't guarantee a unique color using a hash, but it at least saves you from keeping a list of used colors somewhere, and keeps these obscure commands out of your source files (nicely hiding them in one single print.c module).

meaning-matters
  • 21,929
  • 10
  • 82
  • 142