12*******@gmail.com writes:
I have the following 2 C files:
f.c:
#include <stdio.h>
void banana_peel(char c, short s, float f){
printf("char c = %c short s = %d float f = %f \n", c, s, f);
}
1.c:
int main(){
short ss = 7;
char cc = 65;
float ff = 10.0;
banana_peel(cc, ss, ff);
return 0;
}
I use gcc to compile them on Linux, and I see the result is :
char c = A short s = 7 float f = 0.000000
[...]
As Jens pointed out, the problem is that when the compiler sees the
call to banana_peel(), it has no visible delaration for that function,
so it doesn't know how to call it properly. It falls back to certain
default assumptions which happen to be incorrect in this case.
The solution is to add a declaration.
The simplest way is to combine your f.c and 1.c into a single source
file, but that doesn't scale well to very large programs, and I
suspect the whole point here is to learn how to use multiple source
files.
In general, you want to *define* functions in ".c" files and *declare*
them in ".h" files. Here's my version of your program, with an added
"f.h" file:
========================================
==f.h <==
void banana_peel(char c, short s, float f);
==f.c <==
#include <stdio.h>
#include "f.h"
void banana_peel(char c, short s, float f){
printf("char c = %c short s = %d float f = %f \n", c, s, f);
}
==1.c <==
#include "f.h"
int main(){
short ss = 7;
char cc = 65;
float ff = 10.0;
banana_peel(cc, ss, ff);
return 0;
}
========================================
#including "f.h" in "f.c" isn't strictly necessary, but it allows the
compiler to check that your declaration is consistent with your
definition.
For more complex cases, where a header might be #included multiple
times (due to headers #including other headers), you want "include
guards", so the header is only processed once for each translation
unit:
#ifndef H_F
#define H_F
void banana_peel(char c, short s, float f);
#endif
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"