Can we mix c and c++ code - c++

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.

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>.

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.

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.

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

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.

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).

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

To let the C++ compiler know that you are calling C code:
#ifdef __cplusplus
extern "C" {
#endif
void myCFunction();
#ifdef __cplusplus
}
#endif

Related

Can functions from the C standard library be used in C++?

Right now I'm getting familiar with C and the C standard library and I wonder if my knowledge in this area will be useful when I turn to working with C++ at a later time.
Therefore I'd like to know, whether I can use the functions provided by the C standard library in a C++ setting, and also whether and why it would make sense to actually do so.
Yes, C++ was originally designed so that any C library can be easily used in C++. Of course this is slightly less true (in particular, if a C library happens to use some C++ keyword like try or dynamic_cast, it won't work; also, if a callback coded in C++ passed to a C library is raising some exception, you are likely to have a big mess).
The standard practice to use a C header file in C++ is
extern "C" {
#include <some_c_header_file.h>
};
and most existing C header files are designed to cooperate with C++ by actually containing stuff like
#ifdef __cplusplus
extern "C" {
#endif
//// most of the header material goes here, C style
#ifdef __cplusplus
}; // end extern "C"
#endif
In practice, many C standard headers have equivalent C++ headers wrapping things like above (and also in namespace std). Eg C <stdio.h> is C++ <cstdio> -but you often should prefer genuine C++ streams (<iostream>), however printf-like routines are usually more localization friendly mixed with gettext(3).
However C and C++ are very different languages. You should code in idiomatic C++11 (using standard C++ containers, auto, closures, RAII, smart pointers, rule of five, SFINAE, exceptions, anonymous functions, ...)
Some standard C functions are not very useful in idiomatic C++. For example, you are unlikely to use directly malloc in genuine C++ (at least prefer new -which is still very low level and no more in the C++ spirit-, more likely use a lot the containers and the smart pointers without dealing manually with heap allocation). But POSIX functions (notably syscalls(2) ....) are quite useful in C++. longjmp is likely to be incompatible with C++ exceptions.
BTW, C++ has evolved a lot in this century. Don't learn C++98 but at least C++11 (there are tremendous differences between them) and perhaps C++14. Use a recent compiler (GCC or Clang/LLVM); in december 2015, that means GCC 5 at least or Clang/LLVM 3.7 at least. Don't forget to enable all warnings & debug info in the compiler (e.g. g++ -Wall -Wextra -g -std=c++11)
C++ (that means C++11 at least) is a difficult programming language, considerably more complex than C is. You'll need weeks of reading to learn some of it, and good coding style and discipline is essential (you can easily write very crappy code in C++). Start with Programming: Principles & Practice Using C++
I believe that if you only know C, reading SICP (and studying a bit of Scheme) before learning C++ is worthwhile.
The notion of undefined behavior is very important, both in C and probably even more in C++. You absolutely need to understand it (see C.Lattner's blog on it) and avoid it.
You will also learn a big lot by studying (and perhaps contributing to) some existing free software and its source code. Hence I recommend using Linux.
I'll just quote a paragraph out of the ISO/IEC N3690(c++ standard).
17.2 The C standard library
1 The C++ standard library also makes available the facilities of the C standard library, suitably adjusted to ensure static type safety.
So simply yes!
yes .you can use standard c library functions in C++
Examples
stdio.h => cstdio (printf/scanf)
math.h => cmath (sqrt)

When to use printf/scanf vs cout/cin?

I'm testing some snippets I found off the web using g++ from MinGW. This is the C++ compiler...why then does it correctly compile C....why do people intertwine C and C++.
The concrete question is: Is it O.K. to use both C and C++ and compile under g++. If the answer is yes, this makes my life easy as I do not have to modify the code.
Oddly enough...to get some C++ to work, particularly when passing a string to an ifstream constructor it requires a C type string...
My guess would be that because C++ depends upon C constructs at times is is O.K to write the two languages together.
However as a matter of style you should settle on cout/cin or printf/scanf.
There are a few oddities where char* is needed. You can bridge the gap by using the .c_str() method of a std::string to get one.
For the most part, the C subset of C++ is compatible. Exactly how it isn't compatible is not likely to matter for the most part:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
If you're compiling snippets of C code under a C++ compiler, be sure to change it to use the "c" lib format in your includes...for example #include <cstdio> instead of #include <stdio.h>
Is it bad practice to use a C header instead of its C++ equivalent in C++ (e.g. stdio.h instead of cstdio)?
For a fairly reasoned argument from Bjarne himself on why to avoid scanf, check out the beginning of this paper:
http://www.stroustrup.com/new_learning.pdf
There are a lot of benefits to using iostreams instead of printf as well:
'printf' vs. 'cout' in C++
The C++ language inherits much of its core functionality from C. That's because C++ was derived from C. The C++ Standard includes, by reference much of the C Standard. Therefore you can use the C++ compiler to write code using C constructs, idioms and paradigms. Doing so is often referred to as using C++ "as a better C."
The long and the short of the above is yes, you can use printf in C++ code. Doing so is explicitly allowed by the Standard.
Doing this however will often neglect many of the features that define C++. I'll leave that conversation for another question but suffice it to say that many people will tell you simply "don't do that" or "that's not C++." This sets aside the reasons why you might not want to use printf in a C++ program or indeed why you would want to. But rest assured that it is technically allowed.
Is it O.K. to use both C and C++ and compile under g++.
Yes, it is fine to mix the two languages. This is common with code that started out as C, but then got more and more C++ features added (obviously somebody changed the compiler along the way).
Generally, C code will compile and run with a C++ compiler. There are many possible exceptions, such as use of keywords like class and virtual for names of things in C code, or C's relaxed casting rules.
You will often hear people say "they are very different languages". That's because any programming question you ask probably has a different answer depending on which language you're trying to use. However, there are lots of similarities and backwards compatibility aspects as well.
If you use C++, then use C++. (cin,cout)
Why fstream takes c string puzzles me too.

Can you link a C++ library from a C application?

I have cross compiled an open-source library (C++ based) using my G++ cross compiler. I am now trying to use the outputted .a files in my C based application that is built using my GCC compiler... Is that possible?
Yes. Ensure that all functions you want to use are extern "C" and that you only use basic types on the functions you want to use.
If you use the same version GCC as you use G++ it should definitely not be any problem. Cross-version should be ok, but may have very minor incompatibilities. New GCC (3.0+) conform to the Itanium ABI so they'll be fine; they have a binary agreement on how to exchange & format data.
You will need to ensure that the C++ functions called from the C code are declared extern "C" and that their interfaces use only types that can be handled by C (simple types, opaque pointers, etc).
You will probably also need to link the application with the C++ compiler, rather than the C compiler, to ensure that the correct initializations are done for the C++ library. The C++ compiler used for the linking must be 'the same' as the one used to generate the library. That means either the same version of the C++ compiler or a compatible version of it. It usually means that you cannot link with CompilerA (from Vendor A) if the library was produced by CompilerB (from Vendor B); the C++ runtime conventions are such that different compilers (deliberately) use different schemes for supporting different features of C++.
You can link a C application to a c++ library,
BUT you can only include header files containing valid C -- not C++ -- code,
AND any c++ functions you call must have been declared with the extern "C" declaration.
The answer to your question is "yes" but as others have pointed out, there are some considerations, hazards & limitations to what you can do & how you do it.
Just recently in the course of covering this same topic with a client, I came across an article with a pretty good treatment of the topic. The article discusses things like calling C code from C++ code, calling C++ code from C code, linker considerations, function wrappers, exceptions, linkage specifications, and accessing C++ classes from C, etc.
Article: Mixing C and C++ Code in the Same Program
If the C++ library has C++ interfaces you cannot use them directly, you will have to create wrappers that are compiled as C++ but which have extern "C" linkage. The complexity of such wrappers will depend on the natuire of the interfaces, use of C++-only features such as classes, and function/operator overloading will require work to map an OO interface to a procedural one.
The easiest, least-hassle method to do this, assuming your C code is reasonably sane, is to simply build your C application with g++.
Remember, good C code almost always builds in a C++ compiler. Then there are no special considerations, no extern "C" statements to add, no ABI issues, etc, and you can easily use the C++ library to its fullest, regardless of how its functions are declared.

Why is C++ backward compatible with C ? Why isn't there some "pure" C++ language?

C and C++ are different languages, blababla we know that.
But if those language are different, why is it still possible to use function like malloc or free ? I'm sure there are all sort of dusty things C++ has because of C, but since C++ is another language, why not remove those things to make it a little less bloat and more clean and clear ?
Is it because it allows programmers to work without the OO model or because some compilers doesn't support high-level abstract features of C++ ?
Because C++ would be right out dead if it wouldn't be compatible to C the way it is now. No one, except the fanbois, would like C++ if it wouldn't be compatible to C. (I know I'm probably going to be downvoted for this. Be it so!).
About "Why there's no "pure" C++ language... Well, there is at least one. The most popular one is called D, it's great, well-designed, feature-rich, pleasant to code with, and you can use C libraries with it.
Ah, and almost nobody uses it. :)
The direct reason is that C++ is not bad enough to give people a good reason to port millions of lines of their legacy code to more modern, and as you described, "pure" languages like D.
Most operating systems expose a C API, so if you want to use C++ for systems programming, you need some level of C interoperability.
That the C standard library was incorporated into the C++ standard library has historical and practical reasons: C++ began its life as an extension of C, and the C standard library was ready to use. It would be silly to exclude part of the library (like malloc and free) just because there are more idiomatic C++ alternatives: if you want to do stupid things, C++ gives you the power to do so.
For actual language semantics, the same applies - but to a lesser degree - and because of backwards-compatibility, C++ can never be entirely free of its C heritage.
It's designed so that you can port C code and compile it as C++ code directly, and it allows for incremental upgrading of existing code. If C++ didn't have malloc/free, you couldn't compile existing C code as C++, because you'd have to pay some poor shmuck to go through and find all the malloc calls and replace them, which is expensive.
C++ was designed to be compatible with C -- in fact it was originally a superset of C, but the C language has since changed to break that.
This means that C libraries -- including the C run-time library -- can be called from C++ code. It does not mean that it is a good idea to do so!
If you want a "pure" C++ then you can just use C++ without calling any C libraries.
[As others have said since I started typing this: The Design & Evolution of C++ is a good place to start reading for the background on this.]
I suggest you take a look at The Design & Evolution of C++ to get a better feel for the reason the language turned out the way it is. There are historical reasons why C++ grew out of C and was made backward compatible with it.
The early versions of C++ were built on top of C and in fact the compiler translated C++ code to C which was in turn compiled by the local C compiler. Bjarne Stroustrup is a great believer in backwards compatibility and would, I'm sure, resist any attempt to take functionality away.
You can read all about in in Bjarne's book The Design and Evolution of C++.
There were plenty of more pure languages. They didn't get widely used, though, because they were too far outside the comfort range of most programmers. C++, on the other hand, allowed programmers to slowly ramp up by allowing C styles.
What you're doing is looking at languages like C# or Python and wondering why C++ doesn't look like them, but forgetting that getting there required stepping stones like C++ and Java, or Awk and Perl.
To adapt a quotation I heard earlier: C# is Microsoft's version of Sun's for-idiots version of Bell's version of C-enhanced-by-Simula.
All are right. To sum up: the reason is politics. If you want something to be popular, enhance something already popular and you have a ready market. Design something new and no one will be interested unless you are Sun, design some utter crap, but throw billions of dollars into library development and marketing.
malloc() and free() are required so that you can call into C language libraries from C++ code. The C language library might return a pointer to memory allocated with malloc() that must be freed by the caller with free(); or, less commonly, it might require a pointer to memory allocated with malloc() that it can internally reallocate with realloc() or free with free().

Does a C++ standard library have to be written in C or assembly?

Is it possible to write the complete C++ standard library (including STL of course, but self-contained, only internal dependencies) using only C++? I would imagine containers and <cstdlib> functionality would be doable in terms of chars, bitshifts, and for loops and other byte fancy things, but stuff like exceptions and perhaps std::cout and std::cin seem hard to me without a dependency to begin with. Let's say there is a set of OS functions available, that are completely implemented in assembly (to avoid any C contamination).
I'm assuming the compiler understands everything from classes and virtual functions to templates and function overloading, these are language level things and have no place in a library IMHO.
If this has been asked before or is a trivially stupid question, please forgive me. I'm not trying to start a C<->C++ war here, just trying to figure out the limitations of implementing a beast such as the Standard library...
Thanks!
Since pretty much anything written in C can be rewritten fairly easily in C++, you're asking whether assembly code is needed, and the answer is generally no.
Unless we're talking about embedded programming, operating systems have all the necessary file and I/O functionality available through system calls, usually (nowadays) in C format. The library needs to call them, likely through extern "C"{ ... } declarations. The operating system functions are not considered part of the C++ library, and typically aren't exact matches to anything defined in the C++ Standard.
To implement a C++ standard library, you would need to be familiar with the language itself, know the OS calls you're going to use, and have the algorithms you're going to use. At that point, it's a relatively straightforward matter of writing the software.
First thing, it doesn't matter if it's C, C++, or D. Any compilable programming language at the end gives you (mostly) the same assembly object file.
Second thing, STL is written in C++, you cannot write C++ library in C or any other language (well, you can but I assume, that we're talking on reasonable solutions). You cannot implement STL containers in C, because the're strongly use templates.
GCC generate really nice output in asm for exceptions now. I recommend to read about C++ ABI (if you're interested in it).
C++ compiler understands all C++ specific features really nice nowadays. Thanks to really advanced code analysis and optimizations, it's able to produce fast executables (see first paragraph).
I hope that I've at least partly answered your question.
The only piece of C++ that needs assembly is the exception handling. I suppose that it might be doable in C++ if there exist libraries to handle the necessary register and stack management.
Of course, those libraries would then include assembly. There just isn't any other way to do direct register management.
The STL is very heavily reliant on #includeed header files. Those pretty much have to be C++.
Anything that isn't in one of those header files though could in theory be implemented in C, Ada, Assembly, or the other systems-programming language of your choice. However, you'd probably have to be maintaining two interfaces if you don't make at least the top layer C++.