In this project, I need to get the size of a struct in a header file from within a C file.
I can't include the header file in the C file because the struct contains classes which will not compile in C.
Any ideas?
In this project, I need to get the size of a struct in a header file from within a C file.
I can't include the header file in the C file because the struct contains classes which will not compile in C.
Any ideas?
Provide a utility function in your C++:
extern "C" size_t ReturnSizeOfMyStruct(void) {
return sizeof(MyStruct);
}
Then invoke it in your C code:
extern size_t ReturnSizeOfMyStruct(void);
size_t howBig = ReturnSizeOfMyStruct();
You could declare in the .h
file:
extern const size_t SIZE_OF_MY_STRUCT;
And define SIZE_OF_MY_STRUCT
in the .cpp
file as:
extern const size_t SIZE_OF_MY_STRUCT = sizeof(MyStruct);
So you would not have the overhead of a function call.
If the struct
actually is using C++ features (member functions, private
/protected
/public
members, constructor and/or destructor, inherits from another class/struct) [or in turn has members that use any of those features], then you haven't got many choices:
extern "C"
calling convention. There may be some other variants on the above themes, but essentially, assuming it's a "C++ struct" that can't be compiled in C, you're stuck with fixing it in some way that is C++ friendly.
Obviously, if the C++ struct isn't using any C++ features - it's just a plain old data, then the solution is clearly to move the struct out of the current header and place it in a header that can be included in both C and C++.