如何使用另一个c文件中的结构

时间:2018-01-14 17:27:16

标签: c data-structures

它是否可以在C中定位,您在一个.c文件中定义一个结构,但在另一个.c文件中使用它? 基本上,我想使用我已经在另一个程序中创建的List。但我想使用不同的结构。

我有3个文件:

main.c - 另一个程序,我想使用列表

list.c - 列表代码

head.h - 绑定它们的标题

在main.c中:

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

typedef struct cell{
int x;
cell next;
}TCell;

typedef struct{
TCell first;
int lenght;
}List;

#include "head.h"

int main()
{
TCell *c
c->x = 5;
List *l;
init(l);
add(l,c)
c = get();
return 0;
}

head.h:

#ifndef HEAD_H_
#define HEAD_H_
void init(List *l);
void add(List *l, TCell *c);
TCell get();    
(...)
#endif 

list.c

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

#include "head.h"

typedef struct{
TCell first;
int lenght;
}List;

void init(List *l){ (...) }
void add(List *l, TCell *c) { (...) }
TCell get() { (...) }
(...)

但是当我尝试编译它时,它不起作用,因为它缺少head.h和list.c中的TCell,以及head.h中的List

那么,是否有可能在main.c中只有一个TCell的定义,所以每当我改变它的内部变量时,它仍然可以工作?

1 个答案:

答案 0 :(得分:1)

将此设为head.h

#ifndef HEAD_H_
#define HEAD_H_

typedef struct cell
{
    int  x;
    cell next;
} TCell;

typedef struct
{
    TCell first;
    int   lenght;
} List;

void init(List *l);
void add(List *l, TCell *c);
TCell get();    

...

#endif 

并从typedefList中移除TCell list.cmain.c,因为您只需要定义一次类型。

标头文件旨在包含您的共享类型定义。

这是entry of the famous C-FAQ可能会有所帮助。我建议你仔细阅读整个常见问题解答,它会教你很多关于C的事情,并会为你节省很多时间。