5 Reasons to Use C++ for Android Development

shutterstock_278948843

Although Apple and Google champion specific programming languages for mobile development (Objective-C/Swift for Apple’s iOS, and Java for Google Android), independent developers spend a lot of time figuring out how to build iOS and Android apps using other programming languages.

Some alternative languages include C# (Xamarin) and Pascal (Embarcadero-Rad Studio). There’s also the C++ route; for example, DragonFire SDK for iOS and Google Android. Last year, Android Studio added support for the Native Development Kit (NDK) so that developers could use C/C++ in their Java Apps.

So what are the benefits of switching to C++ for Android development? Here are five:

(Somewhat) Faster Code

A number of prominent software titles leverage C++ for cross-platform development, including Facebook Moments, Dropbox, Office, Skype, and popular games such as “Clash of Clans.”

As C++ usually has no standard user Interface, the user-interface code is written in the native language and C++ used for the business logic.

Java, with the JVM-optimized byte-code, can generate pretty fast code, but native (i.e., machine code) can be faster and useful in areas such as gaming, physics simulations and signal processing. Although you can do all of that in Java using JNI for low-level access, that adds a slight overhead—and that may be why native (i.e., C++) has a slight speed advantage.

Visual Studio

Microsoft released the free Express version of Visual Studio in 2005, following that up with the Community edition in 2013, which allows plugins and manages them through the Nuget Package Manager.

Visual Studio supported Visual C++ right from the start (along with the not-at-all popular C++/CLI, which became C++/CX for WinRT). Now C++ can be compiled to target Android and produce Native-Activity Android applications. The platform uses the CLANG toolchain when compiling for Android. (Microsoft developed this capability in-house for its own Android apps development.)

Visual Studio includes a fast Android emulator along with Android Development Kits (SDK, NDK) plus Apache Ant and Oracle Java JDK, so you don’t have to switch to another platform to use external tools. Ant, Gradle and Cmake are included, but there’s also Xoreax Incredibuild, a build system that integrates into Visual Studio 2015 and leverages networked computers for speedier builds.

Existing Game Source Code

There’s a lot of existing game code out there, including open-source game engines and free content. Check out Wikipedia’s list as a starting place; there are some links to resources. While not all games are programmed in C++, the sheer number of assets out there gives you the opportunity to put something together.

Advantages of C++ over Java

Java is an excellent language, but for Android mobile development, C++ has a few advantages. These include a smaller memory footprint, as C++ is nearer the metal and has no garbage collection.

C++ is a superset of C and should compile virtually all C programs, so you could reuse C software. Then there’s the speed issue: it’s often claimed that Java programs can run as fast as C++, and in some cases faster. While I’ve no reason to doubt it (see the section above about JVM), you may need to tweak your Java code to get that level of performance.

Java source code is compiled to bytecode and stored in .jar files, which are zip files. At runtime, the JVM loads the .jar file bytecode and compiles it to machine code. This is JIT: Just-In-Time Compilation.

Compare that to C++, which has no “warm up” time. For that reason, at least in my experience, C++ applications always feel a little snappier than Java (or C#) on the same hardware.

The code below is from the NDK Reference for NativeActivity; it’s the first part of initializing the activity for writing to the OpenGL screen:

void android_main(struct android_app* state) {
    struct engine engine;

    // Make sure glue isn't stripped.
    app_dummy();

    memset(&engine, 0, sizeof(engine));
    state->userData = &engine;
    state->onAppCmd = engine_handle_cmd;
    state->onInputEvent = engine_handle_input;
    engine.app = state;

    // Prepare to monitor accelerometer
    engine.sensorManager = ASensorManager_getInstance();
    engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
            ASENSOR_TYPE_ACCELEROMETER);
    engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
            state->looper, LOOPER_ID_USER, NULL, NULL);

    if (state->savedState != NULL) {
        // We are starting with a previous saved state; restore from it.
        engine.state = *(struct saved_state*)state->savedState;
    }

This simple example below fills the screen with a color. To write to the off-screen buffer, you have to replace the GlClearColor and glClear calls and put your code there. Don’t remove the eglSwapBuffers call or your screen display won’t be swapped in:

static void engine_draw_frame(struct engine* engine) {
    if (engine->display == NULL) {
        // No display.
        return;
    }

    // Just fill the screen with a color.
    glClearColor(((float)engine->state.x)/engine->width, engine->state.angle,
            ((float)engine->state.y)/engine->height, 1);
    glClear(GL_COLOR_BUFFER_BIT);

    eglSwapBuffers(engine->display, engine->surface);
}

(In comparing low-level access, Java arrays are usually safe; slightly constrained; often have overhead while C++ native arrays have optional overhead, are slightly unconstrained and are possibly unsafe.)

C++ Is Already Well-Used on Android

First there was the Google Android NDK. Google states that, while it won’t benefit most apps, it could prove useful for CPU-intensive applications such as game engines. Then Google Labs released fplutil in late 2014; this set of small libraries and tools is useful when developing C/C++ applications for Android. And don’t forget that Google Play Services includes a C++ API.

Conclusion

If you’re an experienced C++ developer who wants to get into Android development, it’s now as easy and zero-cost as programming in Java.

Image Credit: Zeynep Demir/Shutterstock.com

Comments

11 Responses to “5 Reasons to Use C++ for Android Development”

February 09, 2016 at 6:12 am, Game Developer said:

In addition Qt 5.5 works beautifully on Android and QML even has an Android theme (of course it’s not 1:1 the same thing). I’ve been using C++11 + Qt + QML successfully for Android game development. It’s awesome to develop _natively_ on my Ubuntu desktop and then occasionally test on an Android device.

Reply

March 29, 2016 at 8:10 am, Mark Liamey said:

Interesting position, mostly I agree. I work at mobile app development and we always use c++.

Reply

July 11, 2016 at 9:08 am, Sajan P Jose said:

It is easy to develop common gateway interface (cgi) programs using c,c++ ,with web server like lighttpd running in android terminal.
Example : ccoms digital library application

Reply

July 20, 2016 at 8:17 pm, Whiskas said:

Optimized Java cose is very rarely as fast as well optimized c++ code, because c++ offers way more flexibility and optional overhead. Furthermore, having more control over your memory allocations makes your code more cache friendly and much faster than typical object-orientes java code.

Reply

September 16, 2016 at 6:53 am, ben said:

Yeah… But the tools for C++ cross platform development are super expensive… QT is a great example of that…The cost is the main reason why i decided to learn JS + HTML + CSS to write apps for mobile and desktop + the web

Reply

September 04, 2017 at 5:25 pm, Repete Peters said:

JS + HTML + CSS is not an app, it’s a website. (PWAs are not apps either, they’re glorified websites)

Reply

October 17, 2016 at 4:30 pm, EJS said:

Why does this talk about Java bytecode or the JVM? That’s completely irrelevant – Android uses DEX (not Java bytecode) and Dalvik/ART (not the JVM).

Reply

March 15, 2017 at 1:17 am, rupa said:

Re: dalvik/ART: No one likes to know or look what lies under the carpet (java thence convert to dex)… do we? As long things are working no one’s bothered to pay attention; only when issues crop up , suddenly, everyone wakes up with a jolt only to realize that every bit of code is shrouded in layers of code in yet a different language or system. I wonder why they killed maemo native code … ? The old wheel turns and the same spoke comes up …. AGAIN. I win, you lose …. AGAIN!

Reply

March 24, 2017 at 3:26 pm, Ivan said:

C++ is NOT a superset of C. It may compile most C programs, but they will not necessarily run correctly. I can see the point and I sort of agree with it, but I also see that the author doesn’t really know what he’s talking about.

Reply

April 28, 2017 at 10:06 am, the badass said:

people i want to develope apps for android which program do you recommend me??

Reply

October 23, 2017 at 12:48 pm, Mike said:

Android 6 compiles DEX bytecodes ahead of time (AOT) at installation time. Thus no longer being “just” in time. Thus no slower startups. Thus tossing out just about every single excuse how Java is somehow a bad choice instead of C++ (it isn’t).

Reply

Post a Comment

Your email address will not be published.