1

I am new and I know how to color output only in Unix/Linux systems:

#include <stdio.h>

int main(void) {
    printf("\033[1;31mRed Message\033[0m.");
}

But this is not works in Windows cmd.exe, only in Unix terminal.

I am writing cross-platform app and want to know how can I do this in Windows cmd.exe too.

This also does not works:

1.

#include <stdio.h>

int main(void) {
    printf("%c[1;31mRed Message%c[0m", 27, 27);
}

2.

#include <stdio.h>

int main(void) {
    printf("[1;31m Red Message [0m");
}

This works, but I think this is just a bug:

If I type system(""); before printf then it works.

#include <stdio.h>

int main(void) {
    system("");
    printf("\033[1;31m Red Message \033[0m");
}

Thanks

Enty AV
  • 65
  • 4
  • This used to work in windows if the cmd.exe window supported ansi escape sequences. – drescherjm Jul 16 '20 at 14:22
  • Related: [https://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences](https://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences) – drescherjm Jul 16 '20 at 14:22
  • More related info here: https://stackoverflow.com/questions/2048509/how-to-echo-with-different-colors-in-the-windows-command-line – Eljay Jul 16 '20 at 14:46
  • This all not worked in cmd.exe, I saw this URLs already. – Enty AV Jul 16 '20 at 14:50

1 Answers1

0

If you want to make your library crossplatform, I would use the following approach: Have a library, with the same functions, let's say: void printInRed(const char* string). (In a headerfile) After that you write two or more implementations. One for windows:

//TODO: Errorchecking
void printInRed(const char* string){
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    //TODO: Extract magic number
    //See https://stackoverflow.com/a/4053879/13912132
    SetConsoleTextAttribute(hConsole, 12);
    puts(string);
}

And another one for unix-like OS:

//TODO: Errorchecking
void printInRed(const char* string){
    printf("\033[1;31m%s\033[0m.", string);
}

Then you can check at compile time, which version to compile. The first approach is to use #ifdefs, but this will make the code a bit messy.

Another approach would be to use a build-system like CMake to select at build time, which one to build. A buildsystem requires a bit of learning, but will help you to make maintaining a crossplatform library simpler.

JCWasmx86
  • 3,473
  • 2
  • 11
  • 29