c 多个源文件返回错误值

标签 c linux gcc makefile

我正在为我的 Linux 类(class)做一些作业,其中一项作业教我们如何使用 makefile。我已经设法让我创建的 makefile 正常运行,所以别担心,你不会剥夺我的知识。也就是说,我对我的程序的行为感到困惑。

我正在使用 makefile 将 4 个源文件编译成一个程序。 3 个源文件由一个函数组成,该函数本质上只是使用 math.h 中的标准函数来执行计算,返回一个 double 值。例如:

#include <math.h>

double sqroot(double arg)
{
    arg = (sqrt(arg));
    return arg;
}

一个源文件调用所有这三个函数。

#include <math.h>

double sum(double arg)
{
    arg = (sqroot(arg) + square(arg) + sine(arg));
    return arg;
}

主要内容如下:

#include <stdio.h>

void main(int argc, char *argv[])
{
    double num=atoi(argv[1]);
    printf("the sine of %lf in radians is %lf\n", num, (sine(num)));
    printf("the square root of %lf is %lf\n", num, sqroot(num));
    printf("the square of %lf is %lf\n", num, square(num));
    printf("the sum of all of these is %lf\n", sum(num));
}

程序编译没有问题,但是当我运行程序时,它打印出错误的值。

使用 GDB,我检查了每个函数的返回变量的值,结果是正确的,但是在进入 main 后,值不一样了。当我简单地将这些函数放在带有构造函数的 main 中时,程序会按预期运行。

示例终端输出:

eng-svr-1:/home/jhazel/Desktop/Linux/257/hw8>make all
gcc  -c main.c sine.c sqrt.c square.c sum.c -lm
gcc  -o HEYTHERE main.o sine.o sqrt.o square.o sum.o -lm
gcc  -g main.c sine.c sqrt.c square.c sum.c -lm
eng-svr-1:/home/jhazel/Desktop/Linux/257/hw8>./HEYTHERE 2
the sine of 2.000000 in radians is 0.000000
the square root of 2.000000 is 0.000000
the square of 2.000000 is 0.000000
the sum of all of these is 0.000000
eng-svr-1:/home/jhazel/Desktop/Linux/257/hw8>

我的 makefile 构建不正确吗?使用不正确的命令编译?还是我的源文件中遗漏了什么?

最佳答案

感谢 MikeCat 在我的 makefile 中使用 -Wall -Wextra 的建议,我能够确定我没有包含在其他源文件中实现的函数的声明。

为了解决这个问题,我包含了一个带有声明的头文件:

double square(double arg);
double sine(double arg);
double sqroot(double arg);

到 sum 和 main 源文件,另外 double sum(double arg); 到 main。

关于c 多个源文件返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40755322/

相关文章:

c - 在C中查找int类型的长度

C - 数组/结构体讨论

Linux内核编程: can't include header file

python - Python有同步吗?

c - 如何检查我的包装函数系统调用 - read() 是否正确?

c++ - 使用ssh框架加载共享库

c - ERROR stray\327 C 代码未编译

c - 调用 ISHELL_BrowseURL 时出现意外错误 AEE_EBADCLASS

C unsigned long 转换未正确添加

linux - 如何在 Linux 上重置配置文件?