Is it possible to call a C++ function from a C source code?
Please advice.
Many thanks.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You will want to look into the
extern Cconstruct.From the link:
You can also declare/define multiple functions using the
extern Cconstruct are like so:Declaring and d multiple functions using
extern CYou can even wrap
#includedeclarations withextern "C"like so:The above will cause everything in fictional header
myHeader.hto have C linkage, but can cause problems with nested includes – basically, do not use this construct if you can directly modify the header file yourself. It is a last resort technique.Caveats
As Jack Kelly (thanks Jack Kelly!) mentions, be sure that if your C++ code involves exceptions, that they are handled in your function and are not allowed to propagate to C.
Functions defined with
extern "C"linkage cannot be overloaded, as C does not allow multiple functions with the same name.Your C and C++ code have to be compiled with similar compilers, as they need to agree on types, calling conventions, etc.
References, because I can’t do this alone
Thanks to the commenters.