0

Since the zlib is a C library, to use it in a c++ program one would need to use extern "C" when including the header, as in the following test program:

#include <iostream>

extern "C" {
#include <zlib.h>
}

int main()
{
  gzFile file;
  file = gzopen("test.gz", "w");
  gzwrite(file, "hello\0", 6);
  gzclose(file);

  char text[6];
  file = gzopen("test.gz", "r");
  gzread(file, text, 6);
  std::cout << text;
  
  return 0;
}

To my surprise, the code compiles and behaves correctly even if I remove the extern "C". Version of zlib is 1.2.13.

Why does the linkage works even without the extern "C"?

francesco
  • 7,189
  • 7
  • 22
  • 49
  • 2
    `extern C` is used for exporting *from* C++ into C, not necessarily the other way around. C++ understands C symbols just fine, but C has a hard time with C++ due to all kinds of issues, predominantly *name mangling* and such. Many C libraries are set up to work out of the box with C++ as well. – tadman Dec 10 '22 at 22:54
  • 1
    Did you look inside zlob.h? – Severin Pappadeux Dec 10 '22 at 22:55
  • 1
    Take a look at [zlib.h:36](https://github.com/madler/zlib/blob/master/zlib.h#L36). **one would need to use `extern "C"` when including the header** who did teach you to such a code `extern "C" { #include }`? – 273K Dec 10 '22 at 22:56
  • @273 [This FAQ](https://isocpp.org/wiki/faq/mixing-c-and-cpp#include-c-hdrs-nonsystem) from isocpp.org suggests to insert ```extern "C"``` when using C libraries – francesco Dec 10 '22 at 23:02
  • @SeverinPappadeux Ahh, now I see that there is a ```#ifdef __cplusplus```. thanks for the tip! – francesco Dec 10 '22 at 23:02

1 Answers1

2

If you had looked at zlib.h, you would have found very near the top:

#ifdef __cplusplus
extern "C" {
#endif

(and a corresponding close brace near the bottom).

Mark Adler
  • 101,978
  • 13
  • 118
  • 158