2016-11-23 52 views
0

我正在为我的Linux课程进行一些任务,其中一项任务告诉我们有关使用makefile的信息。我设法让我创建的makefile正常工作,所以不用担心,你不会剥夺我的知识。这就是说,我对我的程序的行为感到困惑。c多个源文件返回错误值

我正在使用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不正确?用不正确的命令编译?或者我在我的源文件中丢失了什么?

+0

'double num = atoi(argv [1]);'不错,但气味。为什么不使用'atof()'? – MikeCAT

+6

通过添加选项“-Wall -Wextra”启用编译器警告。你必须在使用它们之前声明你的函数使用它们。 – MikeCAT

+0

'atoi()'是从以前的错误中遗留下来的,因为我没有注意到使用int函数。 '-Wall -Wextra'帮助我识别问题,我已经包含一个头文件来纠正。 –

回答

0

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

为了解决这个问题,我附带声明一个头文件:

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

的总和和主源文件,另外double sum(double arg);为主。

+0

只是要清楚,这不是一个构造函数。构造函数是非常不同的东西。这是一个函数声明。 – MadScientist