Choice of language for portable library - c++

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.

Related

Examples of C interfaces to C++ libraries?

I'm in the process of writing a C interface to a C++ library, and I'm looking for some high-quality examples (or best practices).
So far this one seems pretty promising: http://czmq.zeromq.org/manual:czmq
Any other suggestions?
You could look into the Parma Polyhedra Library as an example of excellent C interface to a well written C++ library. PPL is a free GPL-ed software, notably used inside the GCC compiler.
Another high quality example is the Open Dynamics Engine. It has a C++ backend and a C frontend. Everything is C linkable.
C++ example
C example
If your C++ library is written as COM on Windows. There are tools to automatically generate the C interface for it.
I can suggest FTGL which is a C++ library providing a C interface. Here are two sample programs that achieve exactly the same thing:
C++ version
C version
Note also that FTGL uses the pImpl paradigm in order to achieve binary compatibility across versions. See here why it's good.
Disclaimer: I'm an FTGL contributor.
libGLU (OpenGL Utility Library) is partially written in C++: http://cgit.freedesktop.org/mesa/mesa/tree/src/glu
libzmq is a kind of weird case since the low-level C API was originally meant to look like POSIX sockets, and absolutely not object-oriented (we made it more consistent and organized over time). Meanwhile the actual library is in C++.
The C++-to-C interface is in libzmq/src/zmq.cpp, and consists of a bunch of simple C functions that call the 'real' C++ code.
CZMQ on the other hand aims for something more classy, providing a simple class model with constructors, destructors, containers, private properties, etc. Nothing radical but does turn C into a much more elegant language.
I'm not sure how well the CZMQ class approach would map to a C++ API unless that API was explicitly designed to be mapped.
Disclaimer: I'm the author of most of CZMQ.

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

Pitfalls when converting C++/CLI to C++

I have a library written in C++/CLI and I want to open it up. I want it to be as cross-platform as possible and be able to write bindings to it for other languages to use (Java, Python, etc, etc). To do this, the library needs to be in plain C++ for maximum flexibility. I figure that the logical structures are already there, I just need to replace the .NET libraries it uses with the standard C++ ones. Is this a misguided notion? What should I watch out for when making this transition?
It might be more trouble than it's worth. Here is what you might come across:
There is no garbage collection in C++. This is the big one. This may require a significant redesign of your library just to convert. If you are using at least C++ tr1, or the boost library, you can sort of get there by using shared_ptr, but there are important fundamental differences. For example, you must be wary of circular dependencies. Also, they make debugging difficult without specific support for them in the debugger.
Functions in .Net classes which have no equivalent in C++ stl or the standard library. Probably the biggest hurtle will be any string manipulation code you have written since there are lot of differences there.
Class libraries/assemblies are not built-in to C++ - every platform has its own method of creating dynamic or shared libraries, and there isn't much support for C++ shared libraries - only C libraries in many cases. Be prepared to make everything a static library.
You must manage all your resources yourself.
Never done a port of C++/Cli to C++, but this comes to my mind:
Make sure that you dont have memory leaks. Use smart-pointers instead of gcnew, if possible (if not, make sure your code is exception safe nontheless).
Make sure your libraries interface only consists of builtin types (builtin does not include types of the STL! however this is not coercively necessary if you go open source)

Developing embedded software library, C or C++?

I'm in the process of developing a software library to be used for embedded systems like an ARM chip or a TI DSP (for mostly embedded systems, but it would also be nice if it could also be used in a PC environment). Obviously this is a pretty broad range of target systems, so being able to easily port to different systems is a priority.The library will be used for interfacing with a specific hardware and running some algorithms.
I am thinking C++ is the best option, over C, because it is much easier to maintain and read. I think the additional overhead is worth it for being able to work in the object oriented paradigm. If I was writing for a very specific system, I would work in C but this is not the case.
I'm assuming that these days most compilers for popular embedded systems can handle C++. Is this correct?
Is there any other factors I should consider? Is my line of thinking correct?
If portability is very important for you, especially on an embedded system, then C is certainly a better option than C++. While C++ compilers on embedded platforms are catching up, there's simply no match for the widespread use of C, for which any self-respecting platform has a compliant compiler.
Moreover, I don't think C is inferior to C++ where it comes to interfacing hardware. The amount of abstraction is sufficiently low (i.e. no deep class hierarchies) to make C just as good an option.
There is certainly good support of C++ for ARM. ARM have their own compiler and g++ can also generate EABI compliant ARM code. When it comes to the DSPs, you will have to look at their toolchain to decide what you are going to do. Be aware that the library that comes with a DSP may well not implement the full C or C++ standard library.
C++ is suitable for low-level embedded development and is used in the SymbianOS Kernel. Having said that, you should keep things as simple as possible.
Avoid exceptions which may demand more library support than what is present (therefore use new (std::nothrow) Foo instead of new Foo).
Avoid memory allocations as much as possible and do them as early as possible.
Avoid complex patterns.
Be aware that templates can bloat your code.
I have seen many complaints that C++ is "bloated" and inappropriate for embedded systems.
However, in an interview with Stroustrup and Sutter, Bjarne Stroustrup mentioned that he'd seen heavily templated C++ code going into (IIRC) the braking systems of BMWs, as well as in missile guidance systems for fighter aircraft.
What I take away from this is that experts of the language can generate sophisticated, efficient code in C++ that is most certainly suitable for embedded systems. However, a "C With Classes"[1] programmer that does not know the language inside out will generate bloated code that is inappropriate.
The question boils down to, as always: in which language can your team deliver the best product?
[1] I know that sounds somewhat derogatory, but let me say that I know an awful lot of these guys, and they churn out an awful lot of relatively simple code that gets the job done.
C++ compilers for embedded platforms are much closer to 83's C with classes than 98's C++ standard, let alone C++0x. For instance, some platform we use still compile with a special version of gcc made from gcc-2.95!
This means that your library interface will not be able to provide interfaces with containers/iterators, streams, or such advanced C++ features. You'll have to stick with simple C++ classes, that can very easily be expressed as a C interface with a pointer to a structure as first parameter.
This also means that within your library, you won't be able to use templates to their full power. If you want portability, you will still be restricted to generic containers use of templates, which is, I'm sure you'll admit, only a very tiny part of C++ templates power.
C++ has little or no overhead compared to C if used properly in an embedded environment. C++ has many advantages for information hiding, OO, etc. If your embedded processor is supported by gcc in C then chances are it will also be supported with C++.
On the PC, C++ isn't a problem at all -- high quality compilers are extremely widespread and almost every C compiler is directly associated with a C++ compiler that's quite good, though there are a few exceptions such as lcc and the newly revived pcc.
Larger embedded systems like those based on the ARM are generally quite similar to desktop systems in terms of tool chain availability. In fact, many of the same tools available for desktop machines can also generate code to run on ARM-based machines (e.g., lots of them use ports of gcc/g++). There's less variety for TI DSPs (and a greater emphasis on quality of generated code than source code features), but there are still at least a couple of respectable C++ compilers available.
If you want to work with smaller embedded systems, the situation changes in a hurry. If you want to be able to target something like a PIC or an AVR, C++ isn't really much of an option. In theory, you could get (for example) Comeau to produce a custom port that generated code you could compile on that target's C compiler -- but chances are pretty good that even if you did, it wouldn't work out very well. These systems are really just too limitated (especially on memory size) for C++ to fit them well.
Depending on what your intended use is for the library, I think I'd suggest implementing it first as C - but the design should keep in mind how it would be incorporated into a C++ design. Then implement C++ classes on top of and/or along side of the C implementation (there's no reason this step cannot be done concurrently with the first). If your C design is done with a C++ design in mind, it's likely to be as clean, readable and maintainable as the C++ design would be. This is somewhat more work, but I think you'll end up with a library that's useful in more situations.
While you'll find C++ used more and more on various embedded projects, there are still many that restrict themselves to C (and I'd guess this is more often the case than not) - regardless of whether or not the tools support C++. It would be a shame to have a nice library of routines that you could bring to a new project you're working on, but be unable to use them because C++ isn't being used on that particular project.
In general, it's much easier to use a well-designed C library from C++ than the other way around. I've taken this approach with several sets of code including parsing Intel Hex files, a simple command parser, manipulating synchronization objects, FSM frameworks, etc. I'm planning on doing a simple XML parser at some point.
Here's an entirely different C++-vs-C argument: stable ABIs. If your library exports a C ABI, it can be compiled with any compiler that works on the system, because C ABIs are generally platform standards. If your library exports a C++ ABI, it can only be compiled with a matching compiler -- because C++ ABIs are usually not platform standards, and often differ from compiler to compiler and even version to version.
Interestingly, one of the rare exceptions to this is ARM; there's an ARM C++ ABI specification, and all compliant ARM compilers follow it. This is not true on x86; on x86, you're lucky if a C++ library compiled with a 4.1 version of GCC will link correctly with an application compiled with GCC 4.4, and don't even ask about 3.4.6.
Even if you export a C ABI, you can have problems. If your library uses C++ internally, it will then link to libstdc++ for things in the C++ std:: namespace. If your user compiles a C++ application that uses your library, they'll also link to libstdc++ -- and so the overall application gets linked to libstdc++ twice, and their libstdc++ may not be compatible with your libstdc++, which can (or so I understand) lead to odd errors from the intersection of the two. Considerably less likely, but still possible.
All of these arguments only apply because you're writing a library, and they're not showstoppers. But they are things to be aware of.

To write a bootloader in C or C++?

I am writing a program, more specifically a bootloader, for an embedded system. I am going to use a C library to interact with some of the hardware components and I have the choice of writing it either in C or C++. Is there any reason I should choose one over the other? I do not need the object oriented features of C++ but it does have a stronger type system. Could it have other language features that would make the program more robust? I know some people avoid C++ because it can (but not always) generate large firmware images.
This isn't a particularly straightforward question to answer. It depends on a number of factors including:
How you prefer to layout your code.
Whether there's a C++ compiler available for your target (and any other targets you may wish to use the bootloader on).
How critical the code size is for your application (we're talking about 10% extra maybe, not MB as suggested by another answer).
Personally, I really like classes as a way of laying out my code. Even when writing C code, I'll tend to keep everything in modular files with file-scope static functions "simulating" member functions and (a few) file-scope static variables to "simulate" member variables. Having said that, most of my existing embedded projects (all of which are relatively small scale, up to a maximum of 128kB flash including bootloader, but usually less) have tended to be written in C. Now that I have a C++ compiler though, I'm certainly considering moving to C++.
There are considerable benefits to C++ from simply using references, overloading and templates, even if you don't go as far as classes. Certainly, I'd stop short of using a lot of more advanced features, including the use of dynamic memory allocation (new). Then again, I'd avoid dynamic memory allocation (malloc etc) in embedded C as well if possible.
If you have a C++ compiler (even if it's only g++), it is worth running your code through it just for the additional type checking so that you can reduce the number of problems in your code. The C++ compiler can pick up on a few things that even static analysis tools won't spot.
For a good discussion on many invalid reasons people reject C++, see Dan Saks' article on Embedded.com.
For a boot-loader the obvious choice is C, especially on an embedded system. The generated code will need to be close to the metal, and very easy to debug, likely by dropping into assembly, which quickly becomes difficult without care in C++. Also C tool-chains are far more ubiquitous than C++ tool-chains, allowing your boot-loader to be used on more platforms. Lastly, generated binaries are typically smaller, and use less memory when written C style.
If you don't need to use Object Orientation, use C. Simple choice there. Its simpler and easier, whilst accomplishing the same task.
Some die hards will disagree, but OO is what makes C++ > C, and vice versa in a lot of circumstances.
I would use C unless there is a specific reason to use C++. For a Bootloader you are not really going to need OO.
Use the simplest tool that will accomplish the job.
Write programs in C is not the same as writing it in C++. If you know how to do it only in C++, then your choice is C++. For writing bootloader it will be better to minimize code, so you probably will have to disable standard C++ library. If you know how to write in C then you should use C — it is more common choice for such kind of tasks.
Most of the previous answers assume that your bootloader is small and simple which is typically the case; however, if it becomes more complex (i.e. you need to be able to load from an Ethernet port, a USB port, or a serial port...you need to validate the code that is being loaded before you wipe out your existing code, etc.) you may want to consider C++.
I have also found that the bootloader and the application typically share some amount of common code so you may also want to consider using the same language as your application to facilitate the code sharing.
The C language is substantially easier to parse than C++. This means a program that is both valid C and valid C++ will compile faster as a C program. Probably not a major concern, but it is just another reason why C++ is probably overkill.
Go with C++ and objchoose what language features you need. You still have full control of the output object code as long as you understand the C++ abstractions that you're using.
Use of OO can still run well if you avoid the use of virtual functions. Avoid immutable object types that require a lot of copying in order to pass values, like std::string. But, you can still use features like templates without any real impact on runtime performance.
Use C with µClibc. It will make your code simpler and reduce its footprint. Can be found in: www.uclibc.org.