gpt4 book ai didi

从头文件中声明的另一个文件调用函数

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:04 24 4
gpt4 key购买 nike

我想调用一个在sin.c中的函数,主文件在test1.c中

文件看起来像这样:

文件 test1.c:

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

int main(){
float angle;
double sinValue;

printf("Please enter a angle: ");
scanf("%f", &angle);

sinValue = sin(angle);

printf("the sin value of this angle is: %2.7f.", sinValue);
printf("program terminated");

return 0;
}

这是头文件:

在 sin.h 中:

extern double sin(float angle);

在文件 sin.c 中:

#include <math.h>
#include <stdlib.h>
#define EPSILON 0.0000001;

int fact(int n);

double sin(float angle){

float rad;
float pi = M_PI;
double newSin, oldSin;
double n = 1.0;
double token;


//find the radians
rad = angle * M_PI / 180.0;
newSin = rad;

//find the approxmate value of sin(x)
while((newSin - oldSin) > EPSILON ){

oldSin = newSin;
token = 2.0 * n - 1.0;
newSin = oldSin + pow(-1.0, n) * pow(rad, token) / fact(token);
n++;
}

return newSin;
}

问题是当我编译 test1.c 时错误信息显示:

sin.h:1:15: warning: conflicting types for built-in function ‘sin’      [enabled by default]
extern double sin(float angle);
^
/tmp/ccxzixfm.o: In function `main':
test1.c:(.text+0x39): undefined reference to `sin'
collect2: error: ld returned 1 exit status
make: *** [test1] Error 1

它已经在头文件中声明了,我也包含了那个头文件,所以错误是什么。我很困惑。

先谢谢了,约翰。

我使用“make”命令来编译test1.c

编译过程如下:

zxz111@ubuntu:~/Desktop/sin$ ls
sin.c sin.c~ sin.h test1.c test1.c~
zxz111@ubuntu:~/Desktop/sin$ make test1
cc test1.c -o test1
In file included from test1.c:3:0:
sin.h:1:15: warning: conflicting types for built-in function ‘sin’ [enabled by default]
extern double sin(float angle);
^
/tmp/ccxzixfm.o: In function `main':
test1.c:(.text+0x39): undefined reference to `sin'
collect2: error: ld returned 1 exit status
make: *** [test1] Error 1
zxz111@ubuntu:~/Desktop/sin$ make test1

最佳答案

您需要将两个源文件都传递给编译器。

如果您使用的是 GCC,它将是:

gcc sin.c main.c -o main

尽管您的 fact()函数似乎没有在任何地方定义,一个名为 sin() 的函数已在 <math.h> 中定义你可能想重命名你的。

关于从头文件中声明的另一个文件调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29338023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com