define extern variable inside a function

Viewed 77

Lets say I have an extern function pointer in a header file

extern void (__stdcall * const glEnable) (GLenum cap);

is there a way to define it inside a function, because its definition depends on other stuff

void glInit()
{
    ...
    Lib lib = loadLib("opengl");
    glEnable = procAddr(lib, "glEnable");
    ...
}
1 Answers

You can do this:

// .h file
extern void (__stdcall * glEnable) (GLenum cap);


// .c file
void (__stdcall * glEnable) (GLenum cap) = NULL;

void glInit()
{
    Lib lib = loadLib("opengl");
    glEnable = procAddr(lib, "glEnable");
}

Now, the function pointer is null until someone calls glInit. It is undefined behavior to call that function pointer before calling glInit, and I assume that was your intention anyway.

Related