Click here to Skip to main content
15,881,424 members
Please Sign up or sign in to vote.
2.50/5 (6 votes)
See more:
Hello,
I want a Step by Step which explain how to use a C++ code (function), in a C project.

thank you,
Posted
Comments
Sandeep Mewara 30-Nov-10 5:26am    
No effort & Demanding
Rajesh R Subramanian 1-Dec-10 8:51am    
Do not post your follow-up queries as "Answers". If you do so, they'll be removed. If you have more queries, either edit the original query or use the "add comment" feature to respond to the answerer with your doubts.
crazykuza 1-Dec-10 13:57pm    
Thanks for the link.
But i don't have a clear idea how to did it.
Build a C++ project and use the .obj.
or Create DLL from C++ code.
And Call a extern "C" function from the DLL or .obj, ....

Make sure that all C++ functions that are called by C functions are declared as extern "C". For example:
extern "C" void my_cpp_func();
This makes sure that your functions are exported by the C++ in an old-school fashion. This can be very handy for example when you make a DLL that interfaces with other (not only C) languages and you don't want your DLL to export nasty mangled C++ symbol names.

In the header file of the C++ .cpp that defines the called function you have to do the following trick to make the header valid when included from both C++ and C:

#ifdef __cplusplus<br />
extern "C" {<br />
#endif<br />
<br />
<br />
void my_cpp_func();<br />
// other func delcarations here...<br />
<br />
<br />
#ifdef __cplusplus<br />
}<br />
#endif<br />



Note that you should not use C++ elements in the declaration of these functions like C++ classes and bool data type. If you want to pass complex data than pass around plain C struct pointers.

More detailed answer:

  1. Create a console C++ project in visual studio.
  2. Add x.cpp and implement there your function.
  3. Add x.h and declare there your C++ function as I described above. Don't forget to include this to your x.cpp because the compiler has to know that in the object file of the .cpp file it has to generate C like names (extern "C")!
  4. Add y.c, and include the x.h header. Inside y.c you can call the C++ function from your C functions.
 
Share this answer
 
v5
Comments
crazykuza 2-Dec-10 15:01pm    
thanks very much, its so clear your explanation.
I will try it and reply you.
crazykuza 2-Dec-10 16:16pm    
it's working 5/5.
;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900