Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking error vs. compilation error

Why does double declaration of structs causes a compilation error, while double definitions of functions causes a linking error?

like image 825
Maroun Avatar asked Nov 14 '12 09:11

Maroun


2 Answers

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

like image 177
Omkant Avatar answered Sep 30 '22 23:09

Omkant


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.

like image 42
Luchian Grigore Avatar answered Oct 01 '22 00:10

Luchian Grigore