c++clinker

Linking error vs. compilation error


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


Solution

  • 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