简体   繁体   中英

c multiple source files return bad value

I'm working on some assignments for my Linux course, and one of these assignments teaches us about the use of makefiles. I've managed to get the makefile I created to function properly, so don't worry, you're not depriving me of knowledge. That said, I'm baffled by the behavior of my program.

I'm using the makefile to compile 4 source files into one program. 3 source files consist of a single function, which essentially just uses the standard functions in math.h to perform a computation, returning a double. eg:

#include <math.h>

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

One source file calls all three of these functions.

#include <math.h>

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

The main is as follows:

#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));
}

The program compiles without issue, but when I run the program, it prints bad values.

Using GDB, I've checked the value of the return variable for each function, which come out correct, but after stepping into the main, the value is not the same. When I simply place these functions in the main with constructors, the program functions as expected.

sample terminal output:

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>

Did I construct my makefile incorrectly? compile with an improper command? or am I missing something in my source files?

Thanks to MikeCat's suggestion of using -Wall -Wextra in my makefile, I was able to determine that I had not included declarations for the functions implemented in the other source files.

In order to remedy the issue, I included a header file with declarations:

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

to the sum and main source files, and additionally double sum(double arg); to the main.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM