问题
I have some files written in C that I want to insert into my .NET C++/CLI code.
This C code is huge and has not been written by me, so it would be a hard task to me 'translating' all the code. How can I insert this code and call the functions I need without any compatibility problems?
I used to think that, if C++/CLI is definitely C++ and C is compatible with C++, there is no problem to insert C code into C++/CLI code. But I've read about something called extern "C"
, which made me change my mind.
How can I insert the code into my project, preferably in another file?
Thank you in advance.
回答1:
C++ can run C code without modifications. The only difference is the way the names of functions and variables are encoded. The process is called name mangling.
Just enclose your C code (headers and source) in a extern "C"
block:
extern "C" {
... (C code)
}
All C code must be written in such a block. This tells C++ compiler how to treat function and variable names. Read more about extern "C"
here.
回答2:
What Mario is writing is correct. I am just modifying his example below. Just add all the header file declaration like below and compile you code to use all the function declared in c into your C++ application. Also include c libraries into your make file
as well.
#ifdef __cplusplus
extern "C" {
#endif
//declare your header file here
#include "your c header file"
void foo(int i);//your c function
#ifdef __cplusplus
}
#endif
来源:https://stackoverflow.com/questions/48682152/how-can-i-insert-c-code-into-c-cli-code