nulladdr
nulladdr

Reputation: 561

define extern variable inside a function

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");
    ...
}

Upvotes: 2

Views: 98

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29975

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.

Upvotes: 2

Related Questions