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\n", 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] = '\0'; 28 printf ("The string printed backward is %s\n", string2); 29 }
However, it fails and the compiler produces following error log:
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!
Conflicting Types for Error - Is a common mistake in programming it occurs due to incompatibility of parameters/arguments type in declaration and definition of the function. Let's understand by example: In this program we are finding the average of two numbers and we create a user define function name average().
An “Undefined Reference” error occurs when we have a reference to object name (class, function, variable, etc.) in our program and the linker cannot find its definition when it tries to search for it in all the linked object files and libraries.
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.
You have to declare your functions before main()
(or declare the function prototypes before main()
)
As it is, the compiler sees my_print (my_string);
in main()
as a function declaration.
Move your functions above main()
in the file, or put:
void my_print (char *); void my_print2 (char *);
Above main()
in the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With