如何在不同的文件中使用struct c编程

How to use struct in different files c programming

我得到的错误是 dereferencing pointer to incomplete type,但我在另一个文件中使用了该结构两次并且工作得很好。为什么当我第三次尝试在 main 中使用它时会出现此错误?显然我使用了不同的名称,这意味着它不是完​​全相同的结构。

这里我定义结构体

//bom.h
#ifndef BOM_H_INCLUDED
#define BOM_H_INCLUDED

struct polyinfo {
    int size;
    int poly[];
};

struct polyinfo *createpoly(struct polyinfo *s, int sz, int p2[]){
    int i;
    s=(int*)malloc(sizeof(*s) + sizeof(int)*sz);
    s->size=sz;
    for(i=0;++i<sz;)
        s->poly[i]=2*p2[i];
    return s;
};

int* bom(int s[], int n);

#endif // BOM_H_INCLUDED

这里我用了两次,效果很好

//bom.c
#include <stdio.h>
#include "bom.h"

int* bom(int s[], int n){
    int i;
    int *s2;
    struct polyinfo *s3;//using the structure of polyinfo
    struct polyinfo *s4;//using the structure of polyinfo 2nd time
    s4 = createpoly(s4, n, s);//creating a poly multiply by 2

    printf("printing 2nd:");
    for(i=0;++i<n;)
        printf("%d", s4->poly[i]);
    printf("\n");

    s2=(int*)malloc(n*sizeof(int));
    printf("received n= %d\n",n);
    for(i=0;++i<n;)
        printf("%d", s[i]);
    printf("\n");

    for(i=0;++i<n;)
        s2[i]=2*s[i];

    s3 = createpoly(s3, n, s);//creating a poly multiply by 2

    printf("printing the struct, poly size: %d\n",s3->size);

    for(i=0;++i<n;)
        printf("%d ", s3->poly[i]);

    printf("\n");
    return s2;
}

第三次尝试使用它时出现错误:dereferencing pointer to incomplete type

//main.c
#include <stdio.h>

int main(){
    int i, s[]={1,1,1,0,1};//the pattern that will go
    int n=sizeof(s)/sizeof(*s);//size of the pattern
    int *p;//sending the patt, patt-size & receiving the poly
    struct polyinfo *s5;//using the structure of polyinfo 3rd time
    s5 = createpoly(s5, n, s);//creating a poly multiply by 2

    printf("printing 2nd:");
    for(i=0;++i<n;)
        printf("%d", s5->poly[i]);
    printf("\n");

    p=bom(s, n);

    for(i=0;++i<n;)
        printf("%d", p[i]);

    return 0;
}

如果我尝试在 main.c 中使用 #include "bom.h",错误是 multiple definition

您的代码实际上有两个问题,您需要同时修复这两个问题。只解决一个问题而不解决另一个问题(这实际上是您尝试过的问题)是行不通的。

1) 目前 createpoly() 在 header 中定义(也称为实现),因此 #include 和 header 的每个编译单元将获得自己的定义- 在大多数情况下,这会导致程序不 link。最简单的解决方法是只在 header 中声明函数,并在一个源文件中定义它(最好也包括 header)。有替代方案——例如,在函数定义前加上 static 前缀——但此类选项会产生其他后果(例如,导致每个 object 文件都有其自己的函数本地定义),因此最好避免使用,除非你有特定需要这样做。

2) 前向声明足以声明指针(例如代码中的 struct polyinfo *s5)但不足以取消引用该指针(例如 printf("%d", s5->poly[i]))。在您的情况下,解决方案是在 main.c 中包含 header(具有 struct polyinfo 的定义)。

多重定义链接器错误来自于在头文件中定义函数。

  • 包括所有使用它的文件的头文件。
  • 将函数定义 createpoly 移至 bom.c,但在 bom.h 中保留函数原型。