This code is just a situation that I found in my actual code which is very big so I’m giving this.here in this code the structure “struct node” is not defined it is defined in another c source file.
my c source code:
/* test.c */
1 #include<stdio.h>
2 #include "test2.h"
3
4 void f(struct node * k)
5 {
6
7 }
my header file :
/* test2.h */
1 extern void f(struct node * k);
When I compile this code with gcc to create an object file:
gcc -w -c test.c
I get:
test.c:6: error: conflicting types for 'f'
test2.h:1: error: previous declaration of 'f' was here
I have given the complete prototype of function f(). Why I am getting this error?
Another thing is that when I don’t include the header file test2.h in test.c and explicitly declare the function prototype in test.c, it compiles successfully. Code is below:
/* test.c */
1 #include<stdio.h>
2 void f(struct node *k);
3
4 void f(struct node * k)
5 {
6
7 }
gcc -c -w test.c
No error.
Can you please explain why this time I am not getting an error?
This has nothing to do with the
externkeyword on the prototype (although it’s not necessary).You need a forward declaration for
struct node:Without that forward declaration, the
struct nodeinside the function prototype is local to that particular function prototype.So when the compiler sees the definition of
f()it also sees another different local declaration for astruct nodeand thinks that you have a conflicting declaration forf().See C99 6.9.1 “Scopes of identifiers”:
GCC 4.6.1 gives a nice warning about this for me:
C++ makes function prototype scope apply only to the parameter names (C++03 3.3.3), so you won’t see this problem if you compile the code as C++.