user14416
user14416

Reputation: 3032

Why do I need extern?

I am getting GL function in my code using wglGetProcAddress. The author of the guide (https://sites.google.com/site/opengltutorialsbyaks/introduction-to-opengl-3-2---tutorial-01) says that I need to define functions like this:

extern PFNGLCREATEPROGRAMPROC glCreateProgram;

Using extern keyword. But I tried without it and it works (compilation is successfully complete and the program successfully uses the function). Why do I need this keyword in general and in this case?

Upvotes: 3

Views: 390

Answers (1)

extern tells the compiler that the name defined is in another compilation unit. A global function definition is extern by default. So that covers why it worked in your case.

A place where you'd have to use it, is when defining and declaraing global variables.

If there is a global variable that a compilation unit needs to be aware off (say a mutex), you need to make it available in said unit. But if you do this:

int a; // in global scope

The compiler will try to allocate memory for it in the programs static memory and will give a redifinition error. extern comes to our rescue here. By writing:

extern int a;

We are providing a declaration for the global, but not allocating memory for it.

But since such use of globals is discouraged, you'd rarely see it in use.

Upvotes: 3

Related Questions