Function definition and extern declaration are different ; but GCC does not even warn and passes the compilation

StackOverflow https://stackoverflow.com/questions/16964767

  •  31-05-2022
  •  | 
  •  

Question

I was reviewing a particular code snippet in which function is declared as

int fn_xyz()

but while referencing the function in another .c file, it is defined as :

extern void fn_xyz()

while fn_xyz is called, there is no check for the return values ; GCC-4.7.0 never warned on the above mismatch ; is this expected ?

Was it helpful?

Solution

Each source file (technically, each translation unit) is compiled completely independently of the others. So the compiler never knows that you've declared the same symbol in multiple places. At link time, all type information has been removed, so the linker can't complain either.

This is precisely why you should declare functions in a header that all source files then include. That way, type mismatches will trigger a compiler warning/error.

OTHER TIPS

Since the linking stage happens after compilation (and the compiler doesn't know or care where you link to; like linking to a shared libary), it makes sense that such a test would not be expected of a compiler.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top