Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

conflicting types error when compiling c program using gcc

I tried to compile following program with gcc.

0 #include  <stdio.h>
1 
2 main ()
3
4 {    
5  char my_string[] = "hello there";      
6
7  my_print (my_string);    
8  my_print2 (my_string);    
9}
10   
11 void my_print (char *string)
12 {    
13  printf ("The string is %s
", string);    
14 }
15        
16 void my_print2 (char *string)
17 {
18  char *string2;    
19  int size, i;   
20
21  size = strlen (string);    
22  string2 = (char *) malloc (size + 1);
23
24  for (i = 0; i < size; i++)    
25    string2[size - i] = string[i];
26
27   string2[size+1] = '';    
28   printf ("The string printed backward is %s
", string2);    
29 }

However, it fails and the compiler produces following error log:

  1. greeting.c: 11: error:conflicting types for 'my_print'
  2. greeting.c: 7: error: previous implicit declaration of 'my_print' was here
  3. greeting.c: 16: error:conflicting types for 'my_print2'
  4. greeting.c:8: erroro:previous implicit declaration of 'my_print2' was there

And if I move the my_print and my_print2 functions before the main function, everything goes well. So can anyone explain why the problem happens? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you don't declare a function and it only appears after being called, it is automatically assumed to be int, so in your case, you didn't declare

void my_print (char *);
void my_print2 (char *);

before you call it in main, so the compiler assume there are functions which their prototypes are int my_print2 (char *); and int my_print2 (char *); and you can't have two functions with the same prototype except of the return type, so you get the error of conflicting types.

As Brian suggested, declare those two methods before main.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...