【发布时间】:2021-04-13 21:41:27
【问题描述】:
我正在开发一个 c 程序(一个合成器),我突然遇到了一个问题。
问题出在这里:
我有两个头文件 server.h 和 seat.h,每个包含一个结构。
server.h
typedef struct
{
const char *socket;
struct wl_display *wl_display;
struct wl_event_loop *wl_event_loop;
struct wlr_backend *backend;
struct wlr_renderer *renderer;
struct wlr_compositor *compositor;
struct wlr_output_layout *output_layout;
Seat *seat; // the seat struct from seat.h
struct wl_list outputs;
struct wl_listener output_listener;
} Server;
bool init_server(Server *server);
void run_server(Server *server);
void destroy_server(Server *server);
seat.h
typedef struct
{
Server *server; // the server struct from server.h
struct wlr_seat *wlr_seat;
struct wl_listener input_listener;
struct wl_listener destroy_seat;
} Seat;
Seat *create_seat(Server *server);
void handle_new_input(struct wl_listener *listener, void *data);
void destroy_seat(struct wl_listener *listener, void *data);
主要问题是它创建了一个头文件循环,所以当我编译它时会导致错误。
我已在C header file loops 阅读了有关该问题的信息。我试过这个,它在 struct 的情况下有效,但是当我调用 create_seat() 函数时,它告诉我类型不匹配。在我的情况下,我也在使用typedef,所以这有点令人困惑。
由于实际代码在任何机器上都不好运行(因为它需要依赖等),请使用此代码作为参考,这解释了我的实际问题。
我使用介子构建系统。如果我使用 ninja 编译程序,它会以无限循环结束。
代码如下:
main.c
#include <stdio.h>
#include "server.h"
#include "seat.h"
int main()
{
Server server;
server.id=10;
Seat seat;
seat.id=20;
server.seat=seat;
seat.server=server;
printSeatId(server);
printServerId(seat);
return 0;
}
server.h
#include "seat.h"
typedef struct
{
Seat seat;
int id;
} Server;
void printSeatId(Server s);
seat.h
#include "server.h"
typedef struct
{
Server server;
int id;
} Seat;
void printServerId(Seat s);
server.c
#include <stdio.h>
#include "server.h"
void printSeatId(Server s)
{
printf("%d",s.seat.id);
}
seat.c
#include <stdio.h>
#include "seat.h"
void printServerId(Seat s)
{
printf("%d",s.server.id);
}
meson.build - 在 src 文件夹中
sources = files(
'main.c',
'server.c',
'seat.c'
)
executable(
'sample',
sources,
include_directories: [inc],
install: false,
)
项目文件夹中的meson.build
project(
'sample',
'c',
version: '1.0.0',
meson_version: '>=0.56.0',
default_options: ['c_std=c11','warning_level=2'],
)
add_project_arguments(
[
'-DWLR_USE_UNSTABLE',
'-Wno-unused',
'-Wno-unused-parameter',
'-Wno-missing-braces',
'-Wundef',
'-Wvla',
'-Werror',
'-DPACKAGE_VERSION="' + meson.project_version() + '"',
],
language: 'c',
)
cc = meson.get_compiler('c')
inc = include_directories('include')
subdir('src')
目录结构如下:
<project_folder>
|--->src
| |--->server.c
| |--->seat.c
| |--->meson.build
|
|--->include
| |--->server.h
| |--->seat.h
|
|--->meson.build
我已经给出了与原项目相同的目录结构。
【问题讨论】:
-
这能回答你的问题吗? C++ circular header includes
-
您可以通过在
Server结构之前添加Seat结构的前向声明或在Seat结构之前添加Server结构的前向声明来解决此问题。跨度> -
你能解释一下吗
-
编辑的代码没有任何逻辑,但这是我面临的问题
-
警告:minimal reproducible example 不使用指向相应其他结构的指针。
标签: c gcc struct typedef meson-build