0

I have a header file where I would like to define a few default colors.

typedef struct _color {
    unsigned char r;
    unsigned char g;
    unsigned char b;
    unsigned char a;
} color;

/* Default colors */

// initializes to (0, 0, 0, 0)
color TRANSPARENT;

color color_black;
color_black.a = 255;

color color_red;
color_red.r = 255;
color_red.a = 255;

color GREEN;
GREEN.g = 255;
GREEN.a = 255;

When I compile with clang -I. -c -o image.o image.c, I get the following errors:

In file included from image.c:5:
./image.h:25:1: error: unknown type name 'color_black'
color_black.a = 255;
^
./image.h:25:12: error: expected identifier or '('
color_black.a = 255;
           ^
./image.h:28:1: error: unknown type name 'color_red'
color_red.r = 255;
^
./image.h:28:10: error: expected identifier or '('
color_red.r = 255;
...

This continues for all of the colors I have defined.

I'm not sure why it thinks the variables should be type names, especially when I have already declared them. I have tried using extern and changing the variable names' style to ALL CAPS.

5
  • 3
    color_black.a = 255; You can't write statement at global scope, all such code must go inside a function. If you just want to initialize the variables, write color color_black = { 0, 0, 0, 255 }; instead. Commented Feb 10, 2021 at 7:16
  • btw your struct definition is a c-ism. In C++ you can write struct color { ... }; Commented Feb 10, 2021 at 7:18
  • 3
    Defining global variables in header files is not a good idea. Commented Feb 10, 2021 at 7:18
  • 1
    oh, this is C, not C++ Commented Feb 10, 2021 at 7:18
  • Please remember that C and C++ are two different languages. Do you need an answer for both? Commented Feb 10, 2021 at 7:21

1 Answer 1

2

You are running code outside of a function.

printf("a");

doesnt compile either, so why should assignment expressions?

instead do

color color_black = {0,0,0,255};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.