What is the relationship between C and C++ (more technical approach) - c++

I was reading through Relationship between C and C++ and was interested in a more technical look at the question.
For example, if you want to use threads in C++, would you (assuming a Linux platform) just use pthreads? I know C++ has the STL and the Boost libraries fill in a lot of gaps... but do C++ programmers generally use libraries for C code?
I'm trying to decide if it's worth learning C++ as I already know C (admittedly learning C is not a pre-requisite and can be a disadvantage) but I'm not sure how C++ and C libraries etc all tie in together....

Up through C++03, yes, you'd probably use pthreads. The current draft of C++11 has threading built into the standard library, so you'd probably use that instead (though it's based closely on pthreads, so there's little practical difference between them).
In general, however, yes, it's easy to use C libraries directly from C++, and in the absence of a C++ library for the purpose it's common to use them. For that matter, even when there is a C++ library, some people sometimes prefer to use C libraries anyway.

C libraries are used in C++ constantly. Sometimes they get wrapped in a nicer idiomatic C++ interface, sometimes not. Lots of thin C++ wrappers around C socket APIs, for example, but people often use sockets directly anyway. I directly use various POSIX functions in C++ all the time.
You do need to make sure you already understand C, though (the number of new C++ programmers who try to pass C++ strings directly to C functions expecting C-strings...). And it takes time to learn the best ways to do certain things (that C function that needs a pointer to an array of data? Just give it the address of the first element of your C++ vector, don't manually allocate/build a new array).

If you are just concerned with interoperability of C and C++ library.
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
is a pretty good link.
If you have never done objected oriented programming, I would recommended giving C++ a try. Both are Turing complete language, There is nothing C++ cannot do that C already can't.

Related

Which languages will call C++ with no explicit bridging?

While developing a new product, we decided to go for a mix of C++ and C#, haven been told that bridging them to allow the C# code to call the C++ code would be easy (spoiler, it's not).
We're pretty experienced C++ programmers and not at all C# programmers so we pretty much just had to believe what we've read. A few attempts to call C and Objective-C was promising and we even found a few articles that showed how to make an unmanaged C++ class available in C# -- or at least we thought. The C++ code in the articles, wasn't C++, but instead the horrible monster C++/CLI that Microsoft seems to think is C++. Since we're doing the C# stuff to get some bits "for free" in macOS and Windows, C++/CLI isn't an option either :-(.
Anyway, plenty of people have claimed that it's easy to call C++ code from some specific programming language, but so far, I haven't seen a single one that will allow me to do so (I haven't been paying too much attention to this, so please provide me with an obvious example). C++ invariably always means C with no C++ stuff at all; no namespaces, classes, no stl, lambdas or anything. Just plain dumb C.
So, are there any languages, besides C++(/CLI) that will allow me to do the following:
Create an instance of a class, using a C++ constructor, and dispatch it with a C++ destructor.
Call member functions on an object ( foo f; f.foo();) with a C++ class.
Use std::vector, std::find_if, std::string and other stuff from the stl. Complete coverage of the stl is not required.
Use overloaded functions (i.e. f(), f(int), f(std::string))
Use overloaded operators (foo operator + (foo, foo))
Use C++11, C++14 and/or C++17 features.
Use RAII (rather important IMHO).
Use namespaces.
No. There is no such language.
Unless you count Objective-C++. But that falls pretty much in the same bucket as C++/CLI, in being C++ with some extensions. And C++/CX is another such beast.
There are some interop tools that can work with C++ classes (SWIG for example), but I have never heard of a tool that is capable of instantiating C++ templates (like vector or find_if) on demand.
What languages will call C++ with no explicit bridging?
The short answer to this question is: NONE
Remember that a programming language is a specification written in some technical report, usually in English. For examples, read n1570 (the spec of C11) or R5RS (the spec of Scheme). For C++, see n3337.
Actually, you are interested in implementations, e.g. in compilers and interpreters for your programming languages. These implementations are practically software. And then the answer might become: it depends (notably on the ABI used & targetted by your compiler and system).
See for examples this list of ABIs for Linux.
plenty of people have claimed that it's easy to call C++ code from some specific programming language,
The C calling conventions are quite common, and it might help to declare every C++ function callable from outside as extern "C". But there is no silver bullet, and details matter a lot.
So, are there any languages, besides C++(/CLI) that will allow me to do the following:
list of C++ features skipped
Probably not.
You probably need at least to understand more about memory management approaches. I recommend understanding more about garbage collection, e.g. by reading the GC handbook (at least for underlying concepts & terminology). Learn more about foreign function interfaces (in some cases, the libffi might help) and language bindings.
You might also consider generating some of the C++ or C glue code, maybe with SWIG (or write your own C++ glue code generator).
On operating systems providing dynamic linking capable of loading plugins at runtime (e.g. Linux with dlopen(3)/dlsym(3); but other OSes often have similar facilities) you could even consider generating some C or C++ glue code at runtime in some temporary file, compile it as a temporary plugin, and dynamically loading that plugin. You could also consider JIT-compiling libraries like GCCJIT or LLVM (or libjit).
I recommend reading SICP, the Dragon Book, and probably Lisp In Small Pieces. Of course, learn something about OSes, e.g. Operating Systems: Three Easy Pieces. Reading about Linkers and Loaders could also help.
As an excellent example of cleverly gluing C++, look into CLASP and see this video.
But whatever approach you take, you'll need a lot of work (years, not weeks).
C++ as a language does not have a defined ABI (Application Binary Interface) - which basically means that there is no universal standard of what a C++ class/function call/template would look like in binary form on any given platform, or across platforms.
What that means is that there is no universal way to call C++ code from other languages, on different platforms, or even across compilers on the same platform. It also means that the people who are telling you "it's easy to call C++ code from XYZ language" are mostly incorrect (or at least incredibly incomplete).
Where there are interfaces it's either because the provider of the interface controls the ABI (C++/CLI with .NET), or because there is a translation layer from C++ to something like the C calling convention (Boost::python).
Some work has been done towards attempting to define an ABI per-platform (http://open-std.org/JTC1/SC22/WG21/docs/papers/2014/n4028.pdf), but as far as I'm aware it has not yet been accepted into C++17.
You can look into using C++ interpreter, which allows for the fine-grained control you ask for. But I don't know of any that "just works", see also:
Have you used any of the C++ interpreters (not compilers)?

Implement the C standard library in C++

Say an OS/kernel is written with C++ in mind and does not "do" any pure C style stuff, but instead exposes the C standard library built upon a full-fledged C++ standard library. Is this possible? If not, why?
PS: I know the C library is "part of C++", but let's say it's internally based on a C++-based implementation.
Small update: It seems I've stirred up a discussion as to what is "allowed" by my rules here. Generally speaking: the C Standard library implementation should use C++ everwhere that is possible/Right (tm). I mostly think about algorithms and acting on static class objects behind the scenes. I'm not really excluding any language features, but instead trying to put the emphasis on a sane C++ implementation. With regards to the setjmp example, I see no reason why valid C (which would use either other pre-implemented in C++ C library parts or not use any other library functions at all) here would be violation of my "rules". If there is no counterpart in the C++ library, why debate the use of it.
Yes, that is possible. It would be much like one exports a C API from a library written in C++, FORTRAN, assembler or most any other language for that matter.
Actually, c++ has the ability to be faster than c in many ways, due to it's ability to support many translationtime constructs like expression templates. For this reason, c++ matrix libraries tend to be much more optimised than c, involve less temporaries, unroll loops, etc. With new c++0x features like variant templates, the printf function, for instance, could be much faster and typesafe than a version implemented in c. It my even be able to honor the interfaces of many c constructs and evaluate some of their arguments (like string literals) translationtime.
Unfortunately, many people think c is faster than c++ because many people use OOP to mean that all relations and usage must occur through large inheritance hierarchies, virtual dispatch, etc. That caused some early comparisons to be completely different from what is considered good usage these days. If you were to use virtual dispatch where it is appropriate (e.g. like filesystems in the kernel, where they build vtables through function pointers and often basically build c++ in c), you would have no pessimisation from c, and with all of the new features, can be significantly faster.
Not only is speed a possible improvement, but there are places where the implementation would benefit from better type safety. There are common tricks in c (like storing data in void pointers when it must be generic) that break type safety and where c++ can provide strong error checking. This won't always translate through the interfaces to the c library, since those have fixed typing, but it will definitely be of use to the implementers of the library and could assist in some places where it may be possible to extract more information from calls by providing "as-if" interfaces (for instance, an interface that takes a void* might be implemented as a generic interface with a concept check that the argument is implicitly convertible to void*).
I think this would be a great test of the power of c++ over c.
Given that "pure C stuff" has such a large overlap with C++, I fail to see how you'd avoid it entirely in anything, much less an OS kernel. After all, is the + operation "pure C stuff"? :)
That said, you could certainly implement certain C library functions using classes and whatnot. Implement qsort using std::sort? Sure, no problem. Just don't forget your extern "C".
I see no reason why you couldn't do it, but I also see no reason why someone would use such an implementation. It's going to use a lot more memory, and be at least somewhat slower, than a normal implementation...although it might not be much worse than glibc, whose implementation of stdio is already essentially C++ anyway... (Lookup GNU libio... you'll be horrified.)
Kernels like Linux have very strict ABI, based on syscalls, ioctls, filesystems, and conforming to quite a few standards (POSIX being the major one). Since the ABI has to be stable its surface is also limited. It would be a lot of work (particularly since you need a minimally useful kernel as well), but these standards could be implemented in any language.
Edit: You mentioned the libc as well. That is not part of the kernel, and the language of the libc can be entirely unrelated to that of the kernel, thanks to the aforementioned ABI. Unlike the kernel, the libc needs to be C or have a very good ffi for C. C++ with parts in extern C would fit the bill.

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

Choice of language for portable library

I want to write a library which will be dynamically linked from other programs running on modern operating systems like Windows, Linux and OS/X (i.e. it will be deployed as a .dll or .so module).
What is the most appropriate language in that case? Should I stick with plain C? Or is C++ also ok?
You can use either C or C++ for the implementation, but I would recommend to define the interface in pure C. It will be much easier to integrate.
The difficulty with creating a C++ library distributed in binary form is that your customers - the users of the library - are typically constrained to use the same C++ compiler as you created the library with. This can be problematic if you want to keep up to date and they don't, or if they want to keep up to date and you don't. If you deal in source, this is less of an issue, as long as your C++ is portable enough to allow it to be used by all the compilers your customers use.
If the code may be used from C, I'd probably code to a C interface. Alternative, provide two interfaces - the native C++ interface and a C interface. But that's more work than just a C interface. On the other hand, there may be benefits from a C++ interface (perhaps using STL iterators, etc) and that could sway your decision.
I would also say that C is the lowest common denominator. You always have the option of writing a C++ wrapper to the core library if this integrates better with the calling application.
I'd say C is the most predictably portable, but C++ is doable.
Consider the factor of lowest common denominator and making consumers of your libraries make the decisions that are best for them. The construct of extern c probably still confuses some people and you want your library to travel far and reach the widest audience. Definitely make the interfaces pure c. C++ is fine provided you avoid some of the darker corners (like STL). C is the most portable bar none. Creating libraries for all available platforms is no small feat so be sure to take a look here for some hints. You might also want to consider using autoconf and the like.