I'm writing a simple library to colorize the terminal's text, but maybe i'm doing it wrong.
colors.h:
extern enum col;
extern char* colors[8];
extern char* bold_colors[8];
void printColor(char* color, char* str);
colors.c:
#include <stdio.h>
#include <string.h>
#include <colors.h>
enum col {
BLACK, RED, GREEN, BLUE, YELLOW, PURPLE, CYAN, WHITE, MAX_VALUE
};
char* colors[8] = {
[BLACK] = "\033[0;30m",
[RED] = "\033[0;31m",
[GREEN] = "\033[0;32m",
[YELLOW] = "\033[0;33m",
[BLUE] = "\033[0;34m",
[PURPLE] = "\033[0;35m",
[CYAN] = "\033[0;36m",
[WHITE] = "\033[0;37m"
};
char* bold_colors[8] = {
[BLACK] = "\033[1;30m",
[RED] = "\033[1;31m",
[GREEN] = "\033[1;32m",
[YELLOW] = "\033[1;33m",
[BLUE] = "\033[1;34m",
[PURPLE] = "\033[1;35m",
[CYAN] = "\033[1;36m",
[WHITE] = "\033[1;37m"
};
void printColor(char* color, char* str) {
printf("\033[0;37m");
printf(color);
printf(str);
printf("\033[0;37m");
}
main.c
#include "colors.h"
printColor(colors[GREEN], "text");
The error: identifier "GREEN" is undefinedC/C++(20)
it should share the colors arrays across the files (multiple) but returns an error.
You probably want to move your enum to a header file and include that in both colors.c and main.c
ā Allan Wind
I agree with this.
Programming in C includes compilation and linkage.
At compilation stage, declarations in h-files have effect in c-files, but c-files don't affect each other. Your problem happens here. You fix it by placing all used declarations in your h-file.
At linkage stage, compiled c-files are linked together. Your extern
declarations take effect here. However, they are needed in the compilation stage too, so it's correct to put them in h-files.