Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything special I need to do to use C code in my C++ program?

Tags:

c++

c

g++

Note: I am using g++ version 4.3.4 to compile my C++ code.

So far, whenever I've wanted to use C style language elements in my code it seems that I can just include the C stuff mixed in and alongside my C++.

I know C++ is mostly backwards compatible with C... so I guess my questions are these:

What parts of C are not forwards compatible with C++?

Will professional programmers laugh at me if I continue to naively stick C stuff into my C++ code?

What is the proper way to have C and C++ code in the same .cpp file?

Can I continue to use g++ to compile my hybrid code?

For this question, I am mostly concerned with a solution that deals with a single .cpp file and a single g++ command to compile it. I don't really care about linking stuff at this point.

like image 223
Jimmy Avatar asked Dec 22 '22 10:12

Jimmy


1 Answers

Picking out a couple of questions:

"What is the proper way to have C and C++ code in the same .cpp file?" "Can I continue to use g++ to compile my hybrid code?"

If you want to mix C-style C++ in the same file as regular C++, just go ahead and do it. You can trust the compiler to pick up any issues - they will be minimal and not affect the structure. By the sound of it, you are not interested in getting C-linkage for its own sake, so even if the C-Code is in its own file, compile it as C++. As a matter of fact this is often done as a way of migrating from C to C++.

If you take this approach, your code is not truly hybrid C/C++. It is C++ with some of the code using C-style procedural idioms. C++ is fully intended to support this.

"Will professional programmers laugh at me if I continue to naively stick C stuff into my C++ code?"

It depends where you are using it and why. Well structured C code is good code. Sometimes C+ is much better than C at particular problems. Think hard before using C-style dynamic memory management. You will deserved to be laughed at if you use raw malloc()/free() and get it wrong.

I suggest that if you embark on this approach, you might later take the time to look back and consider whether or not you would have been better to use C++ idioms instread of procedural C.

like image 148
Keith Avatar answered Dec 24 '22 01:12

Keith