I have the following files:
f.c:
#include <stdlib.h>
double f(){
return 12345;
}
main.c:
#include <stdlib.h>
#include <stdio.h>
int main(){
double ret = f();
printf("%f\n", ret);
}
I first compile the f.c into an object file using
gcc -c f.c -o f.o
then combine them using
gcc f.o main.c -o a.out
I’m expecting the output to be 12345.000000, but instead I got 0.000000.
Which step went wrong?
You didn’t compile with enough warnings.
Because you didn’t say:
in the main program, the C compiler was forced to assume the function would return an integer. This mangles the result as the compiler treats 4 bytes of the
doubleas if it were anint, and then converts that into adoubleagain.Your compiler should have warned you about no prototype in scope, unless you’re using a C89 compiler rather than a C99 or C2011 compiler. You should turn on more compiler warnings, so that you get told about such mistakes and don’t run into such problems.
You could provide yourself with a header that declares the function
fand include that header in both code modules. The header acts as a go between, ensuring that the definition is consistent with the usage.