使用main中的头文件中的struct(在C中)

时间:2018-10-10 08:47:07

标签: c struct header-files

我有以下头文件:

#ifndef COMPLEX_H_INCLUDED
#define COMPLEX_H_INCLUDED

typedef struct {
    double r; //real part
    double i; //imag part
} complex;

complex make(double r,double i);

#endif // COMPLEX_H_INCLUDED

和.c文件:

#include <stdio.h>
#include <math.h>
#include "complex.h"

complex make(double re,double im)
{
    complex z;
    z.r=re;
    z.i=im;
    return z
}

现在,当我尝试在主文件中创建一个复数时,我似乎无法打印已创建的复数。

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

int main()
{
    double a,b;
    printf("Enter real, then imaginary part:");
    scanf("%f %f",a,b);

    complex z;
    z=make(a,b);

    printf("The number is: %f%+fi",z.r,z.i);
    return 0;
}

我收到一个错误:未定义的make引用。

1 个答案:

答案 0 :(得分:4)

“未定义引用”错误是由于您没有将编译complex.c所生成的对象文件链接到可执行文件中而导致的。您需要根据开发方式将其添加到链接命令行或项目设置中。我们有一个常见问题解答,它详细介绍了链接的这一方面:What is an undefined reference/unresolved external symbol error and how do I fix it?(常见问题解答适用于C ++,但是链接的这一部分在C语言中是相同的。)


但是,除此之外,您的代码还存在以下问题:

在启用警告的情况下进行构建(您应该总是 总是这样做)会从您的代码中生成这些警告(以及其他):

main.cpp: In function 'main':

main.cpp:28:13: warning: format '%f' expects argument of type 'float *', but argument 2 has type 'double' [-Wformat=]
     scanf("%f %f",a,b);
            ~^     ~
main.cpp:28:16: warning: format '%f' expects argument of type 'float *', but argument 3 has type 'double' [-Wformat=]
     scanf("%f %f",a,b);
           ~^    ~

[Live example]

您正在传递double,而预期的float*,因此该程序具有未定义的行为(并且,如上面的实时示例中一样,很可能会崩溃)。

正确的形式是使用指针作为参数,并为正确的类型使用格式说明符(lf的{​​{1}}):

double

[Live example]