Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing a variable between C and C++ libraries dilemma

I have a simple problem. I have two libraries, one compiled in C, other compiled in C++, where the C library is linked and loaded by the C++ library. I need to declare a struct instance in the C library that both can read and write to. How do you accomplish this?

Thanks

EDIT: added that it's to be an instance of a struct, not just the declaration

like image 946
KaiserJohaan Avatar asked Dec 22 '22 14:12

KaiserJohaan


1 Answers

You need to create a single header file which is included by modules in both the C and C++ libraries:

#ifndef YOURSTRUCT_H
#define YOURSTRUCT_H

#ifdef __cplusplus
extern "C" {
#endif
    struct YourStruct
    {
        // your contents here
    };
#ifdef __cplusplus
}
#endif
// UPDATE: declare an instance here:
extern YourStruct yourInstance;
#endif

This form of header file means that both compilers will be happy reading the header file and both will produce the same name mangling.

Update:
Then you need a module file. Just the one. Either a C file if it is to be included in your C library, or a C++ file if it is to be included in your c++ library:

#include "yourstruct.h"

YourStruct yourInstance;

Now any client of the global instance, whether it is a C client or a C++ client just has to #include "yourstruct.h" and reference yourInstance

Update:
As Matthieu points out you are better off passing pointers to instances around. eg.

#include "yourstruct.h"

#ifdef __cplusplus
extern "C" {
#endif

void yourFunction(YourStruct* someInstance);

#ifdef __cplusplus
}
#endif
like image 59
quamrana Avatar answered Dec 24 '22 03:12

quamrana