Search code examples
c++headerexternlibjpeg

C++ extern not found when in header


I am very new to C++ and I'm trying to do my best to have a good project structure from the beginning. I am using the C library libjpeg and was including it in my .cpp with the use of

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

It worked fine until I removed it to put it in a header file which now gives me the following errors:

inc/jpeg_utils.h: 6: inc/jpeg_utils.h: extern: not found
inc/jpeg_utils.h: 8: inc/jpeg_utils.h: Syntax error: "}" unexpected

My headerjpeg_utils.h :

#ifndef JPEG_UTILS_INCLUDE
#define JPEG_UTILS_INCLUDE
#include <stdio.h>
extern "C" {
    #include <jpeglib.h>
}
int read_jpeg_file(char *filename, int decompression);
void write_jpeg_file(char *filename, unsigned char *image_buffer, int image_width, int image_height, int quality);
#endif

And at the top of jpeg_utils.cpp :

#include "../inc/jpeg_utils.h"

Did I misunderstand the use of a header ?


Solution

  • If you include jpeg_utils.h in a C file, that extern "C" directive will not compile (obviously, C is not C++).

    Add a pre-processor directive to extern "C" only when in fact you compile as C++.

    #ifdef __cplusplus
    extern "C" {
    #endif
    
        #include <jpeglib.h>
    
    #ifdef __cplusplus
    }
    #endif