-2

我想在不同的文件之间共享一个结构。我的问题是:我想访问由某个文件中的函数定义的结构,由另一个文件中定义的另一个函数。

file1.c

    #include<struct.h>
    int main(){

    //I want to access test1 variables here

    printf("%d",test1.x);
    printf("%d",test1.y);
    .
    .
    }




file2.c

        #include<struct.h>
        int fun(){
        .
        struct test test1;
        test1.x=1;
        test1.y=13;
        .
        .
        .


        }


struct.h

struct test{
int x;
string y;
};
.
//Initialize some structure
.
.
}

我做对了..请告诉我我该怎么做..??我无法在 main() 中看到变量 test1

我正在使用 MS Visual Studio 2012

4

3 回答 3

1

是的。几乎你#include可能需要修复。

利用:

#include "struct.h"

<struct.h>表示它在包含路径中找到。(在项目设置中定义,通常只包括标准头文件,例如<stdio.h>。有时它会包括来自外部库的头文件)

#include "struct"手段在当地寻找。所以如果它在同一个文件夹中,它会找到它。(否则您将需要更详细的路径)

您也不能在函数中播种变量。所以test1变量 infun()对任何函数(包括 )都不可见main()。因此,您需要将内容从 传输fun()main()

做到这一点的一种方法是退回它,struct test1这样做很小。

// file2.c
struct test fun() {
    ...
    struct test test1;
    test1.x = 1;
    test1.y = 2;
    ...
    return test1;
}

// file1.c    
int main() {
    struct test1 = fun();

    printf("%d\n %d\n", test1.x, test1.y);

    ...
}

另一种方法是拥有自己的 test1 并使用指针main()给它fun()

int main() {
    ...
    struct test test1;

    // '&test1' means create a pointer to test1.
    fun( &test1 );

    printf("%d %d", test1.x, test1.y);
    ...
}

// "struct test *test1" means 'test1' is a pointer to a 'struct test'
int fun(struct test *test1) {
    ...
    // a->b is the same as (*a).b
    test1->x = 0;
    test1->y = 1;

    ...
}

(似乎 test1.y 是 achar*并且您为它分配了一个数字。这会导致坏事发生,只分配char*给字符串。

于 2013-10-20T07:02:13.260 回答
0

也许你有 2 个错误;

包括 ==> #include "struct.h"

使 test1 全局变量 infile2.c。

在 file1.c 中添加声明

extern struct test test1;
于 2013-10-20T06:51:29.587 回答
0

尝试这个...

结构体.h:

struct test{
    int x;
    int y;
};

文件1.c:

#include <stdio.h>
#include “结构.h”

int main() {

    外部结构测试 test1; //test1 在另一个文件中定义。

    printf("%d",test1.x);
    printf("%d",test1.y);
}

文件2.c:

#include “结构.h”

结构测试 test1 = {1, 13}; // 使其成为全局变量

诠释乐趣(){
    // 结构测试 test1; // f 的成员不能直接在外面使用。
    // test1.x=1;
    // test1.y=13;

    返回0;
}


或者

文件1.c:

#include <stdio.h>

#include “结构.h”

int main() {

    外部结构测试 test1;
    外部无效f(结构测试*);

    f(&test1);
    printf("%d",test1.x);
    printf("%d",test1.y);
}

文件2.c:

#include “结构.h”


结构测试 test1 = {1, 13};

无效的乐趣(结构测试* p){

    p->x = 1;
    p->y = 2;
}
于 2013-10-20T07:01:15.537 回答