gcc - Questions about C Function Prototypes and Compilation -
with following code:
int main(){ printf("%f\n",multiply(2)); return 0; } float multiply(float n){ return n * 2; }
when try compile 1 warning: "'%f' expects 'double', argument has type 'int'" , 2 errors: "conflicting types 'multiply'", "previous implicit declaration of 'multiply' here."
question 1: guessing it's because, given compiler has no knowledge of function 'multiply' when comes across first time, invent prototype, , invented prototypes assume 'int' both returned , taken parameter. invented prototype "int multiply(int)", , hence errors. correct?
now, previous code won't compile. however, if break code in 2 files 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" still give 1 warning (that printf expecting double getting int) errors won't show anymore , compile.
question 2: how come when break code 2 files compiles?
question 3: once run program above (the version split 2 files) result 0.0000 printed on screen. how come? guessing compiler again invented prototype doesn't match function, why 0 printed? , if change printf("%f") printf("%d") prints 1. again, explanation of what's going on behind scenes?
thanks lot in advance.
so invented prototype "int multiply(int)", , hence errors. correct?
absolutely. done backward compatibility pre-ansi c lacked function prototypes, , declared without type implicitly int
. compiler compiles main
, creates implicit definition of int multiply(int)
, when finds real definition, discovers lie, , tells it.
how come when break code 2 files compiles?
the compiler never discovers lie prototype, because compiles 1 file @ time: assumes multiply
takes int
, , returns int
in main
, , not find contradictions in multiply.c
. running program produces undefined behavior, though.
once run program above (the version split 2 files) result 0.0000 printed on screen.
that's result of undefined behavior described above. program compile , link, because compiler thinks multiply
takes int
, never convert 2
2.0f
, , multiply
never find out. similarly, incorrect value computed doubling int
reinterpreted float
inside multiply
function treated int
again.
Comments
Post a Comment