Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error when using extern "C" to include a header in c++ program

Tags:

c++

c

extern

I am working on a school project which requires to work with sheepdog. Sheepdog provides a c api which enables you to connect to a sheepdog server. First i create c source file(test.c) with the following content :

#include "sheepdog/sheepdog.h"
#include <stdio.h>
int main()
{
struct sd_cluster *c = sd_connect("192.168.1.104:7000");
if (!c) {
    fprintf(stderr, "failed to connect %m\n");
    return -1;
}else{
    fprintf(stderr, "connected successfully %m\n");
}
    return 0;
}

then i compile with no error using the following command

gcc -o test test.c -lsheepdog -lpthread

But what i need is to use it with c++ project so i created a cpp file(test.cpp) with the following content :

extern "C"{
#include "sheepdog/sheepdog.h"
}
#include <stdio.h>
int main()
{
    struct sd_cluster *c = sd_connect("192.168.1.104:7000");
    if (!c) {
       fprintf(stderr, "failed to connect %m\n");
       return -1;
    }else{
       fprintf(stderr, "connected successfully %m\n");
    }
    return 0;
}

now, when i compiled using the following command :

g++ -o test test.cpp -lsheepdog -lpthread

I got this error : compilation error message

like image 710
Ilyas Lahmer Avatar asked Mar 12 '23 09:03

Ilyas Lahmer


2 Answers

You can't just wrap extern "C" around a header and expect it to compile in a C++ program. For example, the header sheepdog_proto.h uses an argument named new; that's a keyword in C++, so there's no way that will compile as C++. The library was not designed to be called from C++.

like image 199
Pete Becker Avatar answered Mar 16 '23 00:03

Pete Becker


I agree with @PeteBecker. From a quick look around Google, I am not sure there is an easy solution. Sheepdog is using C features and names that don't port well to C++. You might need to hack sheepdog fairly extensively. For example:

  • move the inline functions out of sheepdog_proto.h into a new C file, leaving prototypes in their place. This should take care of the offsetof errors, e.g., discussed in this answer.
  • #define new not_a_keyword_new in sheepdog/sheepdog.h

and whatever other specific changes you have to make to get it to compile. More advice from the experts here.

like image 29
cxw Avatar answered Mar 16 '23 00:03

cxw