Can functions from the C standard library be used in C++? - 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)

Related

Can we use the POSIX C libraries in c++?

I am new in the field of Linux system programming.I currently program in C and want to switch to c++.
Can we use all the functions defined in POSIX C libraries in c++ without any change ?
In principle you should be able to use any C API from C++; the language includes features to facilitate it, and most C library authors are aware that people want to do this and will take the appropriate steps. For the system programming interfaces specified by POSIX, C++ compatibility is an explicit design goal.
However, you may still encounter problems. In my experience, the most common problems are:
C API headers often dump hundreds of symbols into the global namespace. Some of those symbols may conflict with C++ library symbols, which will get you in trouble if you using namespace std (but you weren't doing that, right?)
C API headers often make heavy use of macros, including macro names that, yep, might conflict with C++ library symbols; std:: won't save you there.
Compiling your program in a strict conformance mode (e.g. -std=c++11 -D_XOPEN_SOURCE=700) may expose bugs in system headers. This is more likely to happen with C++ than C.
A small handful of the POSIX APIs have abnormal control-flow behavior that may interact poorly with C++ exceptions and destructors, depending on how thorough your C library implementor was about avoiding the problem. setjmp and longjmp are obviously a concern here (has anyone done a C library that implements those on top of DWARF-style exception handling?) but so are fork, setcontext and friends, pthread_cancel, pthread_cleanup_push, and probably a few others I can't remember off the top of my head. (I recall a giant, ultimately inconclusive argument between Ulrich Drepper and the GCC C++ guys back in 2004 or so about exactly how pthread_cancel should behave in the presence of destructors.)
If you go beyond POSIX, you may also have problems with:
Headers that don't bother to wrap all the declarations in an extern "C" block when compiled as C++, which means all the function names get mangled when they shouldn't have been, and the link fails.
Headers that don't even bother to stick to the intersection of C and C++. In the worst case, this can cause failures that don't manifest until the program is run. The most common instances of this are:
Blithely using some C++ keyword as a declared-name (e.g. int template;)
Assuming that void * is assignment compatible with other pointer types (e.g. that it is not necessary to cast the result of malloc)
Assuming that struct foo; does not define a typedef-name foo
Note that the headers specified by POSIX frequently contain system-specific extensions that have not been as carefully thought out as the POSIX interfaces themselves.
"Can we use all the functions defined in POSIX C libraries in c++ without any change ?"
Of course you can. Any c-style API can be used seamlessly in c++.

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

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.

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.