Click here to Skip to main content
15,867,915 members
Articles / Mobile Apps / Android

Writing Games with C++ for Android on a PC - Setting Up

Rate me:
Please Sign up or sign in to vote.
4.93/5 (31 votes)
16 Sep 2014CPOL18 min read 70.1K   68   13
A step-by-step beginners guide to setting up a development environment to write games using Cocos2d-X 3.2 on a PC

Introduction

Wouldn't it be great if you could write a program and just have it run on Android, Windows Phone, Windows desktop, Mac, and IOS?

With Cocos2d-x (V3.2 at the time of writing) it is now possible to develop truly native cross-platform games in C++.

While the same code-base can be used across platforms, the development environment is necessarily different - usually Visual Studio on Windows for Windows Phone, XCode on Mac for i-Devices and Eclipse on almost anything for Android.

Setting up the development environment on a PC to develop for Android isn't too hard - just follow these steps & you'll be writing C++ programs for Andorid and Windows in no time! (You still need a Mac to compile for Mac or IOS - but it's the same source code)

Background

One of the common problems in mobile App development is cross-platform development. Do you write the same thing in Objective-C, C++ (or C#) and Java? Do you stick to HTML and Javascript?

I chose to look at Cocos2d-X specifically because it allows me to write a single code-base, using C++, that will run on just about everything.

Although I use a Mac at home, I'm a Windows developer by profession - and I'd like my games to work on as many platforms as possible - so I figured IO'd set up the development environment in Windows too!

(For Mac users see my article at http://www.codeproject.com/Articles/801093/Writing-Games-with-Cplusplus-for-Android-on-a-Mac for details on setting up for a Mac)

Using this article

I'm writing this as a step-by-step guide for people who, like me, are unfamiliar with Android development. There are a few tricks for new players, and gotchas to be avoided, which I've tried to point out.

Some of the information you will need to type in while following along will involve pathnames on your Pc. Rather than typing them in, or copying from the article (which may be hard if your pathnames aren't the same) I recommend using Cmd's lovely feature whereby you can drag-and-drop a file or folder from a Finder window to a Cmd window, and it will insert the path for you.

Points of Interest

I'm writing this almost as I do it for the first time - so rather than a confident, expert tutorial, we may be in for some bumps along the way - so hold on tight!

History

Release 1. 

Downloads

There are a few things you will need to download to set up your PC for developing for Android.

The easiest thing to do is to download them all to a folder where you will be developing for Android. I am using a folder called AndroidDevelopment.

Excluding Visual Studio, there is around 1Gb of downloads here, so you may want to start them off, then go grab a tea (Earl Grey. Black, since you asked) before continuing. 

** YOU MUST NOT HAVE ANY SPACES IN ANY OF THE PATHNAMES USED **

Cocos2d-X 3.2

http://www.cocos2d-x.org/download

I'd recommend downloading the latest stable 3.x release (3.2 currently)

** Make sure you download cocos2d-x and NOT cocos2d-JS **

Eclipse ADT with the Android SDK for Windows

http://developer.android.com/sdk/index.html

ADT stands for Android Development Tools - so what we're getting here is a version of Eclipse (an open source generic IDE) configured for developing for Android.

Some folk don't like Eclipse. I can't say that I know it well enogh to comment, but in my case, my primary environment for Cocos2dx development is Max/IOS - so I only need to use Eclipse for platform-specific tweaks.

In your case you may use Visual Studio as your main IDE, and use Eclipse again just for tweaks.

Android NDK

https://dl.google.com/android/ndk/android-ndk-r9d-windows-x86_64.zip

NDK stands for Native Development Kit - i.e. Native code not Java. 

The link here is directly to the zipped files rather than the page, because you need to download the r9d version.

** don't try to download the latest version (10.x) because it doesn't work with cocos2d-x **

If you're interested in the problems, they are documented at http://cocos2d-x.org/news/307 so may be fixed by the time you read this...

Apache ANT

http://ant.apache.org/bindownload.cgi

Apache Ant is "a Java library and command-line tool that help building software" so now you know.

I used 1.9.4 which was the latest version. There are instructions on the page how to verify your download - follow them if you will or just trust to luck like I did :)

Python

https://www.python.org/download/releases/2.7.8/

I downloaded the 2.7.8 msi

Visual Studio

http://www.microsoft.com/en-au/download/details.aspx?id=40787

You can download VS2013 Express for free. I'm actually using the commercial version, but there should be little difference. For pure Android development you don't need Visual Studio at all - but if you have it it will help show that you can build projects for Windows with the same code base as for Android.

Java

https://www.java.com/en/download/faq/java_win64bit.xml

You need Java installed to run Eclipse. It's free. Make sure you download the right verion (32 or 64 bit) fro your version of windows.

Installing

Download and install VS2013 (as mentioned this is optional, and I won't step through it here).

Run the python msi to install python. I recommend taking the option to Add python.exe to Path as this will make life easier when we're running python later on.

Create a folder that yuo are going to use to store the unzipped files. I created a fiolder C:\Androidl. Make sure there are no apsaces anywhere in the pathname for the folder you chose - and keep the path short - I had problems with pathnames being too long, hence using C:\Android!

I also extracted the long Zipfile names to shorter fokder names - e.g. apache-and-1.9.4-bin.zip was extracted to a folder apache-ant.

Image 1

make sure they are in the location you want to use, as we'll be setting environment variables to point at those locations, so moving in the future will be a bit of a pain.

** Remember that the folder in which you have these extracted folders cannot have a space anywhere in its pathname **

** If you get an error while extracting it may be because our pathname is too long **

Setting up cocos2d-x

Bring up a Cmd window (Windows key, type 'cmd' and press Enter) and change to the cocos2d-x-3.2 directory . (remember, if you have a Cmd window open you can just type 'CD ' then drag the cocos2d-x-3.2 folder to the Terminal window

The setup program for cocos2d-x is called, unsurprisingly, setup! It’s a python script, but we won’t hold that against it.

Type .\setup.py

(If you get 'Unknown command' errors it's because Python either hasn't installed, or hasn't added it's Path to the Path environment variable - or because you haven't opened a new Cmd window since intstalling Python)

The script will run and ask you to “Please enter the path of NDK_ROOT”

This is the pathname of the folder you extracted from the Zip file (android-ndk-r9d) – to make sure I get the paths right I always drag the folder from an open Explorer window into the Cmd Window.

If you do go wrong, you can safely kill the process (ctrl-c) and start again with the setup.py.

Next it will ask you “Please enter the path of ANDROID_SDK_ROOT”. This SDK folder is found inside the ADT Bundle folder you extracted.

So you can drag the folder to your cmd window.

Now you will be asked to “Please enter the path of ANT_ROOT”.

This is the apache-ant ‘bin’ folder

So again, drag the bin folder to the cmd window and press Enter.

The last thing the setup tells you to do is restart terminal (by which it means the CMD window) to make added system variables take effect. So shut down the cmd window, open another and CD to the cocos2d-x folder agin

If you’ve been reading the screen as the setup runs, you’ll see it is just setting some environment variables so it knows how to find stuff. 

Checking the setup

The setup.py checks for the environment variables, and only asks for them if it doesn’t find them. So re-running the setup (after you have re-started the cmd session) shouldn’t prompt you to enter the paths again. If it does, just enter them again!

Creating a new Cocos2d-x project

Cocos2d-x has a command line option to create new projects. All projects are initially cross-platform when created (that is, it creates an empty project for Windows, IOS, Max, Android and then the shared files sit in their own folder, ready for you to play with.)

Let’s call the game ‘Bounce’, we’ll call the package we’re creating ‘com.codeproject.bounce’. The language will be ‘cpp’ (cocos2d-x supports javascript  and lua as well) and we’ll put the source code in a folder within your AndroidDevelopment folder.

So your command line is:

cocos new Bounce -p com.codeproject.bounce -l cpp -d C:/Android

In case it's not obvious, the -p parameter defines the package name, the -l parameter (that's a lower-case L) defines the language and -d.\ defines the Directory in which to put the project. 

It takes a few seconds to copy, then displays a bunch of stuff about changing project names – don’t worry about that for now.

Cocos2d-x project structure

It isn't necessary to know this for the purposes of this article, bit I tought it would be a good time to talk about how Cocos2d-x projects are structured.

In the Bounce folder are the following folders:

Classes

This folder is where all of the cross-platform code you develop for this project will reside

cocos2d

This folder contains the cocos2d-x library source files

proj.android

This folder contains the Project files for your Android project

proj.ios_mac

This folder contains the project files for both IOS and Mac projects

proj.linux

This will currently be more or less empty as cocos2d-x 4.x doesn't currently support Linux as a target

proj.win32

This folder contains the project files for the Windows project

proj.wp8-xaml

This folder contains the project files for the Windows Phone 8 project

Resouces

This folder contains generic resources for all projects

So, the idea is that you open your project in your development environment and just change the code in the Classes folder, and add resources to the Resources folder.

Then you open the specific project in a suitable development environment (probably Eclipse for Android, Visual Studio for Windows and XCode for mac or IOS) and build the project.

Make a change to your code in Classes, and rebuild each project - and deploy to each device!

The really great thing for me about this is that I can use my favourite IDE for most of the development, then just change to the platform-specific one to build for that platform.

Building The Project

Having created the Bounce project,and set the various Environment variables, you now need to build it for the first time.

In terminal again, cd to the proj.android directory inside the Bounce directory

Here is the command to build the project for android.

Type .\build_native.py

This now compiles the project we’ve just created (and, in fact, the whole cocos2d library!)

This will take quite a long time the first time – but not quite long enough for a cup of tea.

You will probably see some build warnings scrollling past-don't worry as long as you don't see Errors!

(If you do see an error, it maywell be because you have the wrong version of the NDK - remember you need r9d - r10 will give build errors)

Opening the Project in Eclipse

To find the Eclipse executable, look in the eclipse folder inside the adt-bundle folder that you extracted. 

Run Eclipse and take the default workspace option.

You need to import the project into Eclipse:

Select File..Import from the menu.

Expand the Android item in the tree, and select Existing Android Code into Workspace

Importing the project into Eclipse

Browse to the folder where you created your project (in my case, the 'Bounce' folder). Select this folder and click 'Open'.

Importing the project 2.

The Import Projects window will show a list of projects to import. You only want to import the libcocos2dx and Bounce projects, for now, so de-select everything else and click 'Finish'.

Selecting the libcocos2dx and Bounce projects

Now it's open in Eclipse, you can take a look at the source code - open HelloWroldScene.cpp from the Classes folder. This is where you would make changes to develop your game.

Image 5

Finishing Touches

You're nearly there!

We need to tell Eclipse where to find the NDK. Remember, cocos has set up an envoronment variable for it, but Eclipse doesn't know about that, you you need to tell it personally.

Find the path for NDK_ROOT by typing Echo %NDK_ROOT% in a cmd window

I get

C:\Android\android-ndk\android-ndk-r9d

Copy this to the clipboard to save typing it. (right-click, sleect Mark, highlight the text and press Enter - intuitive, eh?)

In Eclipse, right-click the Bounce project in Package explorer, and select properties

Expand the C/C++ Build and select Environment

Click the Add button to add a new Environment Variable

Name the variable NDK_ROOT and paste the path from above in the Value

Telling Eclipse about NDK_ROOT

Click OK to close the dialog, then OK to close the properties.

Devices

We need to have a device to run on. Although there are emulators, it is far better to develop and test on a real device to get a realistic idea of performance; Virtual devices are great for experimenting with different screen sizes and different OS versions, though, so I'll talk you through setting up both a real and virtual device.

Setting up a device for testing

The process changed around version 4.2, so I've documented the different processes below.

Note that you may need to reboot your device for this to work (I did, others report they didn't need to) so I would play safe and reboot, if I were you.

Android 4.2+

Go to Settings on your device.

Scroll to the bottom and select About tablet (or About phone)

Scroll to the bottom, and click on Build number seven times. Yes, that’s right, 7 times (it will show you a message when you get there!) If you already have developer options, you'll see a different message, shown in the screenshot.

Setting up the device - step 1

Click ‘back’ and you will see a new option in the Settings – {} Developer Options

The new Developer Options option

Select this option, then select USB Debugging and any other settings you might like.

select the developer options you need

Android < 4.2

I don't have a suitable device to try this on, but am reliably informed that the following steps will turn on USB Debugging.

Go to Setting on your device.

Select Applications

Select Development

Select USB Debugging

USB Driver

Depending on your device, you need to install a USB driver.  Frankly it's ill documented and a sad, error prone process (see the number of posts on it for an idea of how unintuitive it is!)

My recomendation is to search for a driver for your hardware, download it, then in computer Management, find the device under 'Other' (Under Other because it diesn't have a driver yet). Right-click and select Update Driver Software - then browse to the downloaded folder.

It's very poorly documented (e.g. Windows 8 isn't even mentioned in the documnetation, and the Nexus 7 and other more recent devices just don't exist on the relevant Google pages. Just persevere, you'll get there!

Checking Your device

 Make sure your device is plugged into a USB attached to the Mac.

There are two ways to quickly check it's working...

1. If you have Google chrome installed on your Mac
    Go to chroome://inspect/#devices

Results of browsing to Chrome:\\inspect/#devices

In the screen shot above you will see I have a Nexus 7 attached.

2. Open a cmd window
  Type adb devices

  This runs the adb executable that is in the sdk\platform-tools folder within the ADT folder you extracted earlier.

  You should be able to run the command directly (without specifying it's path) because the cocos2d set up added to the path to your environment variables. If you get a 'command not found' error, you may have enter the whole path of the command file - just drag it into the cmdwindow from Explorer. (When I did this for Mac it added it to my executrable search path, when I did it on Windows it didn't)

It's not quite as friendly-looking as the Chrome version, but sifices for a quick check.

Setting up a Virtual device for testing

Whether you have a physical Android device or not, at some point you will want to create a virtual device to test your program on. (in fact, at one point, my Eclipse refused to detect my real device until I had created a virtual device!)

Here's how to create a Virtual Device.

In Eclipse, select Window...Android SDK Manager 

in the SDK manager, you will see a list of all of the revisions of all of the tools - and a status column showing whether they are installed or not.

Choose which you want to test with, and select the SDK Platform and System Image as appropriate.

Unless you are on a really fast internet link with unlimited bandwidth, I'd select only one or two - as they need to be downloaded, and they are not small!

Selecting the Virtual Machines

When you have selected the ones you want, click the Install x packages button.

Accepting the licenses

Check all the Accept and Accept License radio buttons (seriously badly defined form IMHO, so just click around until you have a bunch of green ticks) and click Install.

The images can be fairly large- so time enough for a cup of tea.

Once you have them, go back to Eclipse, and Close Eclipse and re-start it then select Window ... Android Virtual Device Manager

Image 13

Click on the Device Definitions tab

Image 14

Select one of the pre-defined devices from the list, and click Create AVD...

Image 15

This will pre-enter some of the fields in the 'Create new Android Virtual Device' form. Fill in the remaiing values (specifically, select a target and CPU from those you have downloaded, and ** Check the Use Host GPU checkbox **) and click OK

When you're done, click OK then, back at the AVF Manager, select your newly created Virtual Device, and click Start

Starting the Virtual Device can take ages. Be patient!

Running Your Program

That took a lot of setting up, but you are ready to go!

In Eclipse, right-click on the project and select Run As ... Android Application

Assuming your project builds OK (and it should) you may see the Android Device Chooser.

The Android Device Chooser

This will list all of the devices, real or virtual, that Eclipse can see. The top grid shows the currently running devices, the bottom grid shows the virtual devices that are currently not running.

If you don't see this, it means there is only one device available so Eclipse will use it. If you want to use a virtual device while your physical device is attached, the easiest way is to start your virtual device (from the Android Virtual Device Manager accessed from Eclipse via Windows...Android Virtual Device Manager)

If you do see it, select whichever takes your fancy, click OK, and wait for the magic to happen!

Running the Bounce program in the emulator

And here it is! Not much of a game, but this is real, C++, cross platform gaming.

Cross-Platform

I started off this article talking abut cross-platform development - so let's finish up showing how you can run this same app in Windows

Go to the folder that you created your porject in (AndroidDevelopment/Bounce in my case) and browse to proj.win32

There you will find Bounce.sln. Double-click to open in Visual Studio.

Opening the project in Visual Studio

You will see that, in the Classes folder, is the same source we looked at in Eclipse.

Build and run the project on your Windows machine Running in Windows

 

... and you will see the same App as you saw on your Android device.

(The cocos2d-x image you see isn't scaled for the individual device sizes - that's a skill in itself - hence the different apps do look somewhat dissimilar)

So now, even if you hate Eclipse, you can use Visual Studio to write the cpp, and just use Eclipse to build and run the project for Android.

 

Caveats, Notes and other stuff.

While having the ability to run emulators is great, the default emulators are slow. And when I say 'slow' a don't mean just a little slow, not even make-a-cup-of-tea slow, I mean teribly, terribly slow.Honestly, the start up time can be minutes in some cases.

There are ways you can improve this - but the best one (using a snapshot) can't be used because we need to use the host GPU - and the two options are mutually exclusive.

If you are despairing at the speed, do take a google. But don't hold your breath!

If you want to take this further, and start developing games with Cocos2d-x, then there is a lot of help out there, but I warn you, having changed from cocos2d-iPhone (which is still active) through cocos2d-x 2.x (which is still active) to cocos2d-x 3.x (which is pretty new) it can be hard to find out how best to do things.

If you have questions about cocos2d-x I recommend looking at the forums on the cocos2d-x.org site.

To just have a play around, simply open up HelloWorldScene.cpp in the Classes folder in the application, and make some changes.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Devo
Australia Australia
Software developer par excellence,sometime artist, teacher, musician, husband, father and half-life 2 player (in no particular order either of preference or ability)
Started programming aged about 16 on a Commodore Pet.
Self-taught 6500 assembler - wrote Missile Command on the Pet (impressive, if I say so myself, on a text-only screen!)
Progressed to BBC Micro - wrote a number of prize-winning programs - including the best graphics application in one line of basic (it drew 6 multicoloured spheres viewed in perspective)
Trained with the MET Police as a COBOL programmer
Wrote platform game PooperPig which was top of the Ceefax Charts for a while in the UK
Did a number of software dev roles in COBOL
Progressed to Atari ST - learned 68000 assembler & write masked sprite engine.
Worked at Atari ST User magazine as Technical Editor - and was editor of Atari ST World for a while.
Moved on to IBM Mid range for work - working as team leader then project manager
Emigrated to Aus.
Learned RPG programming on the job (by having frequent coffee breaks with the wife!!)
Moved around a few RPG sites
Wrote for PC User magazine - was Shareware Magazine editor for a while.
Organised the first large-scale usage of the Internet in Australia through PC User magazine.
Moved from RPG to Delphi 1
Developed large applications in Delphi before moving on to VB .Net and C#
Became I.T. Manager - realised how boring paper pushing can be
And now I pretty much do .Net development in the daytime, while redeveloping PooperPig for the mobile market at night.

Comments and Discussions

 
QuestionHindi Pin
Member 1558181928-Mar-22 6:10
Member 1558181928-Mar-22 6:10 
GeneralUseful article Pin
Bhuvanesh Mohankumar22-Jul-16 0:07
Bhuvanesh Mohankumar22-Jul-16 0:07 
QuestionGreat article! Pin
Paul Conrad17-Sep-14 9:28
professionalPaul Conrad17-Sep-14 9:28 
AnswerRe: Great article! Pin
_Maxxx_17-Sep-14 11:19
professional_Maxxx_17-Sep-14 11:19 
GeneralMy vote of 4 Pin
newton.saber16-Sep-14 2:17
newton.saber16-Sep-14 2:17 
GeneralRe: My vote of 4 Pin
_Maxxx_26-Sep-14 19:42
professional_Maxxx_26-Sep-14 19:42 
GeneralMy vote of 5 Pin
Afzaal Ahmad Zeeshan15-Sep-14 10:20
professionalAfzaal Ahmad Zeeshan15-Sep-14 10:20 
GeneralRe: My vote of 5 Pin
_Maxxx_15-Sep-14 12:48
professional_Maxxx_15-Sep-14 12:48 
GeneralRe: My vote of 5 Pin
_Maxxx_16-Sep-14 0:48
professional_Maxxx_16-Sep-14 0:48 
Generalabout your article Pin
cci8go4-Aug-14 22:29
cci8go4-Aug-14 22:29 
GeneralRe: about your article Pin
_Maxxx_5-Aug-14 1:01
professional_Maxxx_5-Aug-14 1:01 
QuestionVS2008 Pin
CodeHead4-Aug-14 7:44
CodeHead4-Aug-14 7:44 
AnswerRe: VS2008 Pin
_Maxxx_4-Aug-14 15:51
professional_Maxxx_4-Aug-14 15:51 
Thanks!

I'm fairly certain you need VS2012 or 2013 - I did quickly try and open the test solution in VS2010 but was met with many errors Frown | :( I don't have time at the moment to investigate further - and as VS2013 is a free download - probably quicker to just use that rather than try to get it working in 2008!
PooperPig - Coming Soon

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.