在项目中的不同文件之间共享结构

时间:2013-10-20 06:38:48

标签: c++ c

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

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

3 个答案:

答案 0 :(得分:1)

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

使用:

#include "struct.h"

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

#include "struct"表示本地查找。所以,如果它在同一个文件夹中,它会找到它。 (否则你需要更详细的路径)

此外,你不能在函数中种子变量。因此,test1中的fun()变量对任何函数都不可见(包括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);

    ...
}

另一种方法是让main()拥有test1并使用指针将其赋予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似乎是char*并且你给它分配了一个数字。这会导致 不好的事情发生,只将char*分配给字符串。

答案 1 :(得分:0)

也许你有2个错误;

include ==&gt; #include“struct.h”

make test1全局变量infile2.c。

在file1.c中添加声明

extern struct test test1;

答案 2 :(得分:0)

试试这个......

<强> struct.h:

struct test{
    int x;
    int y;
};

<强> file1.c中:

#include <stdio.h>
#include "struct.h"

int main() {

    extern struct test test1;    //test1 defined in another file.

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

<强> file2.c中:

#include "struct.h"

struct test test1 = {1, 13};     // Make it a global variable

int fun() {
    // struct test test1;    // member of f can't directly be used outside.
    // test1.x=1;
    // test1.y=13;

    return 0;
}

<小时/> OR

<强> file1.c中:

#include <stdio.h>

#include "struct.h"

int main() {

    extern struct test test1;
    extern void f(struct test*);

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

<强> file2.c中:

#include "struct.h"


struct test test1 = {1, 13};

void fun(struct test *p) {

    p->x = 1;
    p->y = 2;
}