Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force that part of a c++ compiled as C

Tags:

c++

c

struct

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.

like image 391
mans Avatar asked Dec 19 '17 13:12

mans


People also ask

Can I compile C code in C++ compiler?

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.

How do you call a C++ function that is compiled with C++ compiler in C?

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

Can I write C code in C++?

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

What does extern C means?

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.


1 Answers

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!");
like image 62
StoryTeller - Unslander Monica Avatar answered Oct 03 '22 18:10

StoryTeller - Unslander Monica