Why crc32 value require -lz

5.7k views Asked by At

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?

1

There are 1 answers

4
Sourav Ghosh On

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