Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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();

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:

  1. Write a function that returns the size, which is compiled as C++ but with extern "C" calling convention.
  2. Reorganise your code such that you don't need sizeof(C++ struct) in your C code in some other way.
  3. Change your C code so that it's compatible with C++ and compile it with C++ compiler.

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++.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top