Initialize EGL for OpenGL ES 2 in the Android NDK


I’m starting to learning OpenGL ES 2 to write app’s for Android using the Android NDK. Maybe Android isn’t the best system to start learning this, but most of the time I have for this kind of stuff I’m not at home, so learning it on my Android device is currently the only reasonable way for me to learn it.

I try to initialize EGL in my main.c file, but in the line

display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

I get some compile warnings and errors:

  • warning: data definition has no type or storage class
  • error: conflicting types for ‘display’
  • note: previous definition of display was here (pointing to the
    line with this code: EGLDisplay display;
  • warning: initialization makes integer from pointer without a cast
  • error: initializer element is not constant

Here is the source of my main.c file:

#include <jni.h>
#include <errno.h>

#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>

#include <android/log.h>
#include <android_native_app_glue.h>

EGLint majorVersion;
EGLint minorVersion;
EGLDisplay display;

display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

if(display == EGL_NO_DISPLAY)
// Unable to open connection to locale windowing systen

if(!eglInitialize(display, &majorVersion, &minorVersion)
// Unable to initialize EGL.

Can someone please tell me, what I’m doing wrong and how to fix it?

You can not write statements in the global scope in C, they need to go in functions.
Id suggest dropping the idea of learning both OpenGL & C at the same time.

Take your time with C, possibly following some book on it.
Alternatively go with Java (if you are familiar with it) and jump on GL from there.

Hi kyle_,

many thanks for your answers, it helped me to solve the problem.

I played a lot with the SDK but I really like to to 2d and 3d graphic stuff in the future and the performance with OpenGL is not the best using it from the java side. Another important thing is that I like to write code that I can later port to other platforms.

I learned a lot about C++ in the last couple of months and made this in C only because the default native activity example comes with a main.c file. I never used C before so I wasn’t aware of this fact.

Thanks to your hint it was easy to change the file extension to .cpp, change the entry in the file and put the code in a main function. Now it compiles fine.

I was so frustrated because I feared that things work different from the normal EGL implementation and could nothing find about it in the NDK documentation or by searching the web. Now you saved my day!

Many thanks for your help.