Modern Libraries Mean a Revitalized C++

Screen Shot 2015-07-22 at 4.18.15 PM

Developers have relied on C++ for years as a workhorse language, even as many of them graduated to PHP and Perl for building Web applications and other platforms.

While C++ never truly went away, it’s enjoyed something of a resurgence over the past few years. That’s due in no small part to the rise of more modern libraries that allow you to do more with less code and build modern applications more quickly than in the past. So let’s look at some of these libraries you might want to use in your next project; there are many out there.

Asynchronous and Event-Based Programming

Asynchronous and event-based programming are nothing new, but they meet an important need that up until recently has been complicated to handle in C++. In the early days of network programming, you could write a function that would respond to incoming data from the modem; but when your program called the system function to await incoming data, it opened up the possibility of the function holding and not returning, which would prevent the program from doing anything else (if the function returned, your program could continue). This is known as synchronous programming, and it’s obviously not desirable as your program is effectively frozen until data arrives.

Asynchronous programming, while more flexible, is also more complicated to program. If you want to do event-based, asynchronous programming in C++, you can find some pretty nice libraries to help you out.

Take libevent, which is a C library that you can also use in your C++ programs. The libevent library is open source and used in many projects, including the Chrome browser and the memcached caching system. (Memcached uses libevent to help keep straight its multiple threads and passing of data between threads; also for handling the expiration of data by setting a timer event, which can then run without the memcached code having to periodically check the current time.)

To learn how to use libevent, start with the libevent homepage and its documentation, then look at example code such as memcached’s main code.

Check out the latest C++ jobs.

There are a couple of alternatives to libevent. One is libev, also written in C, which can be used in your C++ programs. The author claims it’s closely modeled after libevent but without the bugs (caveat emptor).

Libev received a lot of notice when it was used to provide the asynchronous event look in Node.js. However, recent versions of Node.js have abandoned libev because of problems porting it to Windows, creating another alternative: libuv, also a library written in C that can be used in your C++ programs. Although it was developed for Node.js, it’s a general-purpose C library capable of use outside of Node.js.

Parallel Programming

Parallel programming techniques have been taught in schools for years. Once the sole domain of powerful supercomputers, parallel-programming algorithms are now executable on even the most basic laptops and desktops. But while those algorithms are cool, they’re also complex, which translates into lots of potential bugs.

Right now in the C++ world, one parallel-programming library seems to be taking the lead: OpenMP, which helps to reduce the headaches you encounter when writing multithreaded code that spans multiple cores. It also helps with vectorized code (in which you perform a single operation on multiple values all stored in a single, wide register).

But with OpenMP, there’s a catch: It requires more than just a downloadable library; the compiler must specifically support it, because it relies on pragmas for declaring parallel code. (Fortunately, most compilers today do support it, including the GNU C++ compiler.)

Another library that’s useful for parallel programming is Threading Building Blocks (TBB), essentially a C++ template library for creating parallel code. In order to succeed with TBB, you must fully understand the concept of templates—otherwise you face a steep learning curve.

HTTP, REST, and Web Data

These days, there’s a widespread need for HTTP programming, such as calling RESTful APIs. While some APIs include SDKs that simplify calling them, others require you to make your own HTTP calls.

Making HTTP calls is pretty easy with the right library, but an understanding of the asynchronous nature I described earlier is vital. You don’t want to use a synchronous library with an asynchronous framework because a call into a synchronous library “blocks,” preventing your code from continuing onwards. One nice option is a library called restclient-cpp; Making HTTP calls is as simple as this:

[cpp]

RestClient::response r = RestClient::get("http://secure.pubword.com:3010");

cout << r.body << endl;

[/cpp]

The call is synchronous; it will block until the data is received. If you need asynchronous HTTP requests, I recommend first picking an asynchronous library, then finding an HTTP library built specifically for that library. The libevent library has such features built right in—check out this example on Stack Overflow. You create a request object, fill in the headers, provide the URL and so on, and finally make the request, which calls a callback function that you provide.

JSON

The fact that browsers speak in JavaScript and, by extension, JSON means that any Web-based software you write will need to similarly understand JSON. So when your software receives JSON data, do you want to parse through the JSON manually, or do you want to let a library convert the JSON data into C++ objects?

For mapping the data, there are two approaches; one is to try to map a JSON object directly to a C++ object that has the same structure. For example, this JSON object:

[js]
{
  name: ‘Fred’,
  size: 42
}
[/js]

might end up mapped onto a C++ structure like so:

[cpp]

class Item {
   char *name;
   int size;
};

[/cpp]

Many developers I know have found that trying to do a one-on-one mapping from JSON to a fixed C++ structure can prove problematic, simply because of the static typing in C++. Instead they opt for a library that stores JSON data in containers that you can easily manipulate in your C++ code.

For this approach, I’ve found the JsonCpp library quite effective (you can check out some samples on this project page). Notice the library provides a type called Value that includes overloaded operators, providing a clean syntax such as obj[“name”] that returns another Value instance. This is a bit more complex than simply using a plain old object, but it’s still pretty simple.

XML

For completeness, since we’re talking about HTTP and RESTful interfaces, I should include XML, even though it seems to be falling out of favor. XML has been around for ages, so there are some solid libraries for handling it. The same problems present in handling JSON in C++ exist in handling XML.

The old standby for XML is called SAX, which is, quite frankly, somewhat of a pain to use in my opinion. It doesn’t do any mapping into objects or containers; instead, it parses through the XML by providing functions that handle XML elements and tags as the parser encounters them. In other words, instead of getting a data structure of some sort, you dynamically read through the data. It’s a completely different approach.

Many projects are moving away from XML to JSON, and many RESTful APIs give you the choice of receiving JSON or XML; if you’re determined to use an XML library that maps data the way the JSON libraries do, there are some premium libraries available, discoverable with a quick Google search.

Conclusion

When searching for libraries, be sure to choose ones that are actively maintained. (I prefer libraries that were started at least a couple years ago and have been through a couple major versions.) An actively maintained library generally contains fewer bugs and offers more user feedback.

I also make sure the project is updated regularly (i.e., at some point within the past few months). This is easy to check on GitHub.

Next, always review the licensing; some libraries don’t allow commercial use, and some require that your software use the same licensing. If you’re writing code for a corporation, you might have other requirements, such as if support is available for the library. These are all vital to both the success and legal requirements of your project.

Finally, check the activity level of the community around the library. If you can’t find anyone actually using the library, then you might look elsewhere.

Finding the right library can take time, but when you do, it can greatly speed up your development and free you up to focus on actually building your app.

Image Credit: Max Griboedov/Shutterstock.com

Post a Comment

Your email address will not be published.