Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...