I want to define a struct in a c++ source code that should be a POD (so it should be compiled based on C standard and not C++)
for example assume that I have the following code inside a c++ file:
struct myStruct
{
int x;
int y;
}
class MyClass
{
int x;
int y;
}
if I compile this code, struct is POD and should be compiled as POD. So the placement of member variables follow the C standard which is well defined.
But assume that a user may mistakenly, change the code to this code:
struct myStruct
{
int x;
int y;
private:
int z;
}
class MyClass
{
int x;
int y;
}
now the struct is not POD and compiler is free on how it would place the member variables in memory.
How can I force the compiler to make sure that a struct is always compiled based on C standard?
Please note that I can not place the code inside a *.c code as I am developing a header only code which can be included into a *.cpp source code.
Any C compiler that is compatible with the Oracle Developer Studio C compiler is also compatible with the Oracle Developer Studio C++ compiler. The C runtime library used by your C compiler must also be compatible with the C++ compiler.
Just declare the C++ function extern "C" (in your C++ code) and call it (from your C or C++ code). For example: // C++ code: extern "C" void f(int);
If you are compiling the C code together, as part of your project, with your C++ code, you should just need to include the header files as per usual, and use the C++ compiler mode to compile the code - however, some C code won't compile "cleanly" with a C++ compiler (e.g. use of malloc will need casting).
The extern “C” keyword is used to make a function name in C++ have the C linkage. In this case the compiler does not mangle the function.
You can't force the translator to treat it "as C". But you can add an assertion that it is compatible with C code.
#include <type_traits>
struct myStruct
{
int x;
int y;
};
static_assert(std::is_pod_v<myStruct>, "Violated POD-ness of myStruct!");
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