关于访问在不同源文件中定义的结构

时间:2012-05-03 09:33:21

标签: c struct

没有任何作业,但在做基础时似乎迷路了,因此要求。

说我有2个C源文件。 1.c& 2.c

2.c如下:

typedef struct mystr_
{
    int a;
    float b;
}mystr;

void fun()
{
    mystr q;

    some code....
}

1.c如下:

#include "stdio.h"

void fun();


main()
{
    //How to access / declare a variable of type mystr here.

    mystr *v1;//This obviously gives compiler errors

      some code....    

}

如何从文件1.c访问2.c中定义的结构mystr以获得该结构类型的变量?

编辑:

抱歉忘了在OP中提及。由于某种原因,我无法在头文件中移出声明 - >我试图检查现有代码是一个快速的黑客攻击。那么有没有办法直接从其他源文件访问它?

1 个答案:

答案 0 :(得分:3)

使用标题。

创建文件2.h

typedef struct mystr_
{
    int a;
    float b;
}mystr;

并将其包含在1.c

#include "2.h"
#include "stdio.h"

void void fun();

编辑: 因为您无法将声明提取到头文件中并包含它,所以除了复制声明之外别无他法。这是一个非常脆弱的结构,快速但主要是脏的,除非你没有其他选择,否则不推荐。