Why does double declaration of structs causes a compilation error, while double definitions of functions causes a linking error?
Because functions definitions are included in executable at link time but decalration or syntax check all are done at compile time
Consider one thing also when you are calling any function and compiler is not able to find the declaration of function then it will generate warning as implicit declaration of func()
.
To remove this warning message we provide forward declaration of func,int func();
and it compiled without any warning message.
Do you think why does this happen ? It happens because compiler did not find that func()
symbol. It's all upto the compiler to make code error free according to the Grammar of the Language.
But building of final executable is done at link time and then linker started looking for function defition of func()
, If found then fine and if not .. then Linker error
could not have resolved external symbol _func()
Note: any external symbols are resolved at link time
On gcc for only compilation use this : (this may vary according to compiler)
gcc -Werror -c test.c
--> It will generate test.o
file
then try to link it and make executable
gcc -Werror -o test test.o
--> test
is executable
The standard doesn't say when an error should be reported - it's up to the compiler, but basically it's because that's when the errors are caught.
First, the compiler parses the files. It's easy to see if a struct
or class
was defined multiple times in the same translation unit (only this is an error, between translation units you can have multiple class-type definition), because it deals with that translation unit.
Second, it links the object files together (linking). Only now can it tell that the same symbol was exported multiple times, because that's when the error occurs per-say.
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