Chris Smith
Chris Smith

Reputation: 3012

Having trouble with headers

I'm fairly new to C, and am having an issue with my header file structure. It seems that when I include keyboard.h from ps2.h, since keyboard.h originally included ps2.h first, ps2.h cannot access keyboard.h's definitions.

keyboard.h

#ifndef KEYBOARD
#define KEYBOARD

#include "ps2.h"

typedef enum {
    KEY_UNDEFINED,

    // letters
    A,
    B,
    ... many more keys
} Key;

typedef enum {
    TYPE_UNDEFINED, PRESSED, RELEASED
} KeyEventType;

typedef struct {
    Key key;
    KeyEventType type;
} KeyEvent;

#define NULL {KEY_UNDEFINED, TYPE_UNDEFINED}

... function declarations, implemented in a keyboard.c file next to keyboard.h

#endif

ps2.h

#ifndef PS2
#define PS2

#include <stdbool.h>
#include "keyboard.h"

#define keycount 17

KeyEvent scanCodeSet1[] = { NULL, { ESCAPE, PRESSED },
    { DIGIT1, PRESSED }, { DIGIT2, PRESSED }, 
    ... many more codes
};

I include keyboard.h in my main file.

So like I said above, all the definitions (such as RELEASED) accessed from ps2.h don't work.

The many error messages fit this pattern:

'PRESSED' undeclared here (not in a function)

I'm using GCC if that helps.

Upvotes: 0

Views: 95

Answers (1)

chqrlie
chqrlie

Reputation: 144695

There is a major problem in your keyboard.h file:

#define NULL {KEY_UNDEFINED, TYPE_UNDEFINED}

You should not redefine NULL. It is defined in the standard library include files and it is very important to not provide a conflicting definition such as this one.

Regarding the include order issue: this is what is happening:

  • You include "keyboard.h"
  • keyboard.h defines KEYBOARD
  • keyboard.h includes "ps2.h"
  • ps2.h defines PS2
  • it includes "keyboard.h" recursively
  • keyboard.h checks if KEYBOARD is defined, it is, the contents is not parsed.
  • ps2.h defines scanCodeSet1 with symbols from keyboard.h that have not been defined yet because the recursive inclusion was skipped and the enclosing parse of keyboard.h has not seen them yet.

You can correct this problem by either:

  • not including ps2.h from keyboard.h
  • moving the inclusion of ps2.h after the definitions that are required there.
  • include both headers from the C files.

It is not a good idea to have 2 include files include one another, you should reorganize your definitions to avoid that:

  • use a single header file
  • use a third header file included by both keyboard.h and ps2.h that defines the symbols needed by both.

Upvotes: 1

Related Questions