With the following code:
int main(){ printf("%f\n",multiply(2)); return 0; } float multiply(float n){ return n * 2; } When I try to compile, I get one warning: "'%f' expects 'double', but the argument has type 'int'" and two errors: "conflicting types for 'multiply'", "previous implicit declaration of 'multiply' was here."
Question 1: I am guessing that it's because, given the compiler has no knowledge of function 'multiply' when he comes across it the first time, he will invent a prototype, and invented prototypes always assume 'int' is both returned and taken as parameter. So the invented prototype would be "int multiply(int)", and hence the errors. Is this correct?
Now, the previous code won't even compile. However, if I break the code into two files like this:
#file1.c int main(){ printf("%f\n",multiply(2)); return 0; } #file2.c float multiply(float n){ return n * 2; } and execute "gcc file1.c file2.c -o file" it will still give one warning (that printf is expecting double but is getting int), but the errors won't show up anymore and it will compile.
Question 2: How come when I break the code into 2 files, it compiles?
Question 3: Once I run the program above (the version split into 2 files), the result is that 0.0000 is printed on the screen. How come? I am guessing the compiler again invented a prototype that doesn't match the function, but why is 0 printed? And if I change the printf("%f") to printf("%d"), it prints a 1. Again, any explanation of what's going on behind the scenes?
-Wall -Wextra -Werror -std=c18(you can use other versions of the standard if need be, but not-ansior-std=c90), This will avoid a lot of problems. If you have two source files and one contains a function that the other calls, you need a header file that both source files include which contains a declaration for the function(s) that both use.