Question about the structure of C / C ++

Suppose you have a .cpp file (that is, compiled using a C ++ compiler such as MSVC). In this file, you define struct as follows:

 struct Pixel { float x, y; }; 

In the same file, you have a line of code that calls a C function that requires a C struct equal to Pixel . If you write:

 Pixel my_pixel // set my_pixel to something c_func(&my_pixel); 

Will this work? I mean that the C ++ compiler will create the my_pixel object, but it will pass it to a function that is compiled as C code (I only have .lib for this library).

+4
source share
2 answers

If the header file is correct, it will work, assuming that the C compiler and the C ++ compiler use compatible calling conventions. Make sure the header file has the corresponding extern "C" block that contains the function definition.

+5
source

The reason David Schzwartz says you need an extern "C" block is because without an "C" block, the extern compiler "beckons" the name of the C function you are calling at the point you are calling. If you call the C function, not the C ++ function, the function definition in your library will not have a malformed name, so your executable will not be able to reference.

This is what you want if the function you are calling is written in C ++, since the name mangling allows you to overload the name of the function. The types of each function parameter are compactly encoded in the name of the changed function.

Initial guidance was initially provided in C ++ to allow C ++ object files to communicate with legacy linkers, rather than providing a specialized C ++ linker that has explicit support for overloaded functions.

C does not allow function name overloading, so C function names are never garbled. To provide a prototype in C ++ for a single C function, you do this:

 extern "C" Foo( int theInt ); 

If you have an entire header file full of C function prototypes, and you want to #include this header from a C ++ source, enclose #include in an extern C block

 extern "C" { #include "Foo.h" } 
+1
source

All Articles