How ansi escapes are handled are terminal dependent, and since cmd is your current terminal, that what decides what to do with those escapes.
Basically, what happens when you call printf
, it just sends bytes to stdout. The terminal reads stdout and decides what to do with it.
The problem here has absolutely nothing to do with the compiler. If it is your code or cmd depends on how you view things. If you're using a HP printer with a Dell printer driver, is the problem with the printer or the driver? None of them. They just don't match.
Obviously, your terminal cannot handle those escapes, so if you want to print with color, you'll have to find another way.
These questions might be relevant:
colorful text using printf in C
C color text in terminal applications in windows
So what you can do on Windows is this:
#include <windows.h>
#include <stdio.h>
// Some old MinGW/CYGWIN distributions don't define this:
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
#endif
static HANDLE stdoutHandle;
static DWORD outModeInit;
void setupConsole(void) {
DWORD outMode = 0;
stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if(stdoutHandle == INVALID_HANDLE_VALUE) {
exit(GetLastError());
}
if(!GetConsoleMode(stdoutHandle, &outMode)) {
exit(GetLastError());
}
outModeInit = outMode;
// Enable ANSI escape codes
outMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if(!SetConsoleMode(stdoutHandle, outMode)) {
exit(GetLastError());
}
}
void restoreConsole(void) {
// Reset colors
printf("\x1b[0m");
// Reset console mode
if(!SetConsoleMode(stdoutHandle, outModeInit)) {
exit(GetLastError());
}
}
int main(void) {
setupConsole();
puts("\x1b[31m\x1b[44mHello, World");
restoreConsole();
}
I also found this link about wrappers to be able to use ANSI escapes in Windows:
https://solarianprogrammer.com/2019/04/08/c-programming-ansi-escape-codes-windows-macos-linux-terminals/
As far as I know, there is no portable way of printing with colors in C.