从 C 中的不同文件返回结构

Returning struct from different file in C

最近在C语言中遇到了从另一个文件返回struct的问题。 这是 main.c 的代码:

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


int main()
{
    hashinfo info;

    info = numerator();

    printf("%d\n", info.ppower);

return 0;
}

和numerator.c:

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

hashinfo numerator()
{
    hashinfo info;

    info.ppower = 15;

return info;
}

这是头文件的样子:

typedef struct hashinfo{

    unsigned long a_str;
    unsigned long a_int;
    unsigned long b_int;
    unsigned long p;
    unsigned long m;
    char w;
    char ppower;
}hashinfo;

当我尝试编译代码时,gcc 无法编译 main 报告

main.c: In function ‘main’:
main.c:10:7: error: incompatible types when assigning to type ‘hashinfo’ from type 'int'
  info = numerator();
       ^

如果我把所有这些都放在一个文件中并编译,它会工作得很好。我究竟做错了什么?提前致谢。

那么您认为 main.c 部分(顶部)如何知道 numerator() 返回的类型?您将如何通知 main.c 它将引用特定签名的功能?潜在地,您可以创建一个单独的文件,只包含您的函数的原型,并让所有模块都包含它。 "proto.h" 或类似的。

马克

如果不以某种方式包含它,您就无法告诉您的主要内容 numerator() returns。通常认为包含 .c 文件是不好的做法,但尝试将 #include "numerator.c" 添加到 main.c 的顶部以查看。

您必须在要使用它的任何地方声明您的 numerator 函数。这就是最小声明的样子

hashinfo numerator();

但更好的办法是用原型声明它

hashinfo numerator(void);

并在定义中做同样的事情。

一种典型的方法是将声明放入头文件中,并将其包含在您要使用此函数的任何地方。您的 hash_types.h 是否合适,由您决定。

在头文件 hash_types.h 中添加 numerator() 的声明。在 hash_types.h 末尾添加:hashinfo numerator();