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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With