Programmer
Programmer

Reputation: 6753

Can we mix c and c++ code

I was reading this website

http://www.cplusplus.com/reference/clibrary/cstring/strcmp/

which is a C++ website.But, it uses printf to display things. However, i thought in c++, we use cout to display things. Can we mix c and C++ code as they have done here.

Upvotes: 1

Views: 538

Answers (8)

qquipp
qquipp

Reputation: 1

To let the C++ compiler know that you are calling C code:

#ifdef __cplusplus
extern "C" {
#endif

void myCFunction();

#ifdef __cplusplus
}
#endif

Upvotes: 0

Richie
Richie

Reputation: 31

yes you can mix the 2 codes, but then the resultant code should be in C++ if you are reluctant to edit for compatibility with C. C++ is backward for most of the code

Upvotes: 0

Yuushi
Yuushi

Reputation: 26080

C++ contains (most of) C as a subset (although this isn't a strict subset). If you #include <cstdio> you can use things such as printf, however, unless you have a really good reason, you should stick with using C++ constructs (std::vector, std::cout, new, delete, etc).

Upvotes: 1

Sufian Latif
Sufian Latif

Reputation: 13346

Of course you can! But make sure you're saving the code in a .cpp file. Some compilers wouldn't compile C++ code in a .c file.

Upvotes: 1

Mysticial
Mysticial

Reputation: 471587

Technically speaking, yes you can mix C and C++ code. C++ is a near super-set of C and has all of the C libraries (save for a few slight differences).

However, whether or not you should mix C and C++ is another story. Generally speaking, if you write in C++, you should stick to C++ constructs.

Upvotes: 3

AndersK
AndersK

Reputation: 36067

In C++ the C-runtime is available since C++ is to a great degree compatible with C by design in order to be backwards compatible. That said, if you are programming C++ you should avoid using the C run-time as much as possible since C++ offers much more in terms of functionality and safety. e.g. vector, string

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 181097

Yes, C and C++ are (with very few exceptions) both possible and easy to mix. One example where you may have problems is mixing printf and cout, output may not come in the order you expect.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182893

There is no mix of C++ and C code. While you certainly can use cout in C++, you can also use printf. The vast majority of things that are legal C code are also legal C++ code. In fact, section 27.8.2 of the C++ standard requires printf to be defined if your code #include's <cstdio>.

Upvotes: 7

Related Questions