简体   繁体   中英

How to include c header file in another header?

I'm writing ac program using curses library, and want to create some structs reflecting my application UI.

Here's my app.c file

#include <stdlib.h>
#include <stdio.h>
#include "screen.h"

int main() {
    struct screen scr = {
        .win1 = {
            .title = "win1"
        },
        .win2 = {
            .title = "win2"
        }
    };
}

here's screen.h

#ifndef SCREEN_H
#define SCREEN_H

#include "window.h"

struct screen {
    struct window win1;
    struct window win2;

    struct window *focused;
};

#endif

and here's window.h

#ifndef WINDOW_H
#define WINDOW_H

#include "screen.h"

struct window {
    char *title;
    void (*handle_key_event)(struct screen*);
};

#endif

My window struct handle method must receive a reference to screen, to be able to change the focused window in some specific cases. But when I compile this, I get the warning

window.h:8:34: warning: its scope is only this definition or declaration, which is probably not what you want

which is because it doesn't see the screen declaration. How to fix this?

The warning is when the first reference to a struct is inside something else.

Put struct screen; above the declaration of struct window .

Circular dependencies of header files is a bad idea. Consider refactoring. You do not need the definition of a struct to declare pointers to it. The forward declaration will suffice.

This is about fundamental design, nothing else. To have two header files that mutually include each other simply doesn't make any sense, don't do this. #include is to be regarded as a one-way dependency. In program design, more complex objects depend on/consist of less complex ones.

For example a screen contains a window, so it should be the one doing #include "window.h" . While a window doesn't know a thing about screens, it should only concern itself with displaying a window. Cross-communication between the two modules might have to be in a third module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM