3

I am generating a crc32 value by using crc32(initial_crc_value,data,data_length); . if I am not using -lz in linker options, I am getting linker error as

"undefined reference to crc32".

I did not include any zlib.h. So, in which header file crc32() is declared? Why linker option -lz is sufficient to compile?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
user4790894
  • 49
  • 1
  • 3
  • In which file crc32() is declared? – user4790894 Jun 22 '15 at 08:08
  • 1
    @user4790894 declaration and implementation are not the same thing. You can't compile if you just *declare* `crc32`. You have to have an *implementation* of it, which is in libz.so – Eregrith Jun 22 '15 at 08:09

1 Answers1

4

Firstly, the crc32() function is declared (prototyped) in zlib.h and defined in the zlib library. So, to use the crc32(), you need to include the header and link with the library.

Now, coming to your questions,

1. if I am not using -lz in linker options, I am getting linker error

Yes, because at the linking time compiler will not able to find the crc32() function definition without linking to the zlib library, which contains the function definition.

2. why linker option -lz is sufficient to compile?

To be truthful, it is not sufficient and it should be producing error. However, your code works (compiles) without the header file, is because of the implicit declaration of a function is (sadly, still) supported by the compiler. If you enable proper warnings, you'll be at least warned by your compiler regarding this issue.


Regarding the "implicit declaration" of a function, the scenario is, if the compiler comes across a function call for which it did not see a prototype yet (In other words, have no information regarding the function definition), it assumes the function is defined with a return type of int and accepts any number of arguments. You can read more on this on the related answer

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • How to enable proper warnings in gcc? – user4790894 Jun 22 '15 at 08:38
  • If the compiler considers the function as implicit declaration, then what is the implementation of the function? is it link with libz.so or not? – user4790894 Jun 22 '15 at 09:03
  • @user4790894 see [this](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html) article. However. most of the time, adding `-Wall` to your compilation statement will do the job for warning you for _almost_ all the _possible_ pitfalls. – Sourav Ghosh Jun 22 '15 at 09:18
  • @user4790894 even with an implicit declaration, if you're linking with the library, at compilation time it will find the same function. However, if the function signature differs (i.e., returns anything other that `int`), and the return value is used. it will invoke [undefined behaviour](https://en.wikipedia.org/wiki/Undefined_behavior). – Sourav Ghosh Jun 22 '15 at 09:20