程序仅适用于 .h 文件中的 {} 符号

Mik*_*łaj 0 c split header-files code-splitting

我有三个文件。为什么程序仅适用于 .h 文件中的 {} 符号?

szereg.c:

    #include "szereg.h"

double szereg(double x, double eps, int *sw, int *M, int *stop){ 

    double s, w;
    int i = 2;
        s=x;
        w=x;
    do{ 
        if(*sw==*M){
            if(fabs(w)<=eps && *sw==*M)
                *stop =3;
            else
                *stop = 1;
            return s;
        }
        w=((-w*x)/i)*(i-1);
        s=s+w;
        *sw+=1;
        i++;
    } 
    while (fabs(w) >= eps); 

    *stop = 2;

    return s; 
}
Run Code Online (Sandbox Code Playgroud)

szereg.h:

    double szereg(){};
Run Code Online (Sandbox Code Playgroud)

主文件:

        #include <stdio.h>
        #include <math.h>
        #include <stdlib.h>
        #include "szereg.h"

        FILE *fw; 
        extern double szereg(); 

        int main(){ 

            int lp, sw=1, M, stop = 0;
            double a, b, dx, x, y, eps, z; 
            char *stopwar = "";



            if((scanf("%lf %lf %d %lf %d", &a, &b, &lp, &eps, &M) != 5) || a<=-1 || b>1 || eps<0.0 || lp<1){ 
                printf("Blad danych\n"); 
                system("pause"); 
            exit(1); 
        } 

        if(!(fw = fopen("wyniki.txt", "w"))){ 
            printf("Blad otwarcia zbioru\n"); 
            exit(2); 
        } 

        dx=(b-a)/lp;

        for(x = a; x <= b + 0.5*dx; x += dx){ 
            y = szereg(x, eps, &sw, &M, &stop); 
            z = log(x+1); 

            sw=1;
        } 

        fclose(fw); 
        exit(0); 
        system("pause"); 
    } 
Run Code Online (Sandbox Code Playgroud)

dat*_*olf 5

让我猜猜:如果没有花括号,您将在未解析符号的行中收到链接器错误。

事情是这样的,这两个语句对编译器来说是完全一样的:

extern double szereg();
double szereg(); // without {} is exactly the same as with extern
Run Code Online (Sandbox Code Playgroud)

它告诉编译器的是,有一个符号szereg属于一个函数,它返回一个双精度值并接受未指定数量的参数。然而,它不会将不同的编译单元“粘合”在一起。

您需要做的是将每个.c文件分别编译为一个目标文件,然后在最后的链接步骤中将所有目标文件链接在一起。到目前为止,您可能只链接了主对象文件,而没有链接其他任何内容。