Search code examples
c++openglheaderundefinedidentifier

Identifier defined by a combination of headers?


Recently I ran into a identifier undefined error, but was surprised to find that it was because there were "two" imports missing, rather than one. I.E.

#include <a.h>

int main(int argc, char ** argv)
{
    foo();
    return 0;
}

would not compile because "foo" was undefined.

#include <b.h>

int main(int argc, char ** argv)
{
    foo();
    return 0;
}

also would not compile because "foo" was undefined.

however:

#include <a.h>
#include <b.h>

int main(int argc, char ** argv)
{
    foo();
    return 0;
}

was fine. I'm not sure how this is possible. Does anyone know what's going on here? Why is it that foo() is somehow defined by the combination of these two headers and not either of them individually?

For completeness, this happened during some fiddling with OpenGL on windows. the exact code that produced this behavior was:

#include <Windows.h>
#include <gl/GL.h>
int main(int argc, char ** argv)
{
    glClear(1);
}

where glClear was undefined if either of the two headers was missing. For clarity, the error in both cases was "Error: Identifier "glClear" is undefined"


Solution

  • Using preprocessor directives, you can silently "hide" pieces of code in compile time.

    For example, if a.h has:

    #define A_INCLUDED
    

    b.h may have:

    #ifdef A_INCLUDED
    void foo(void) { return; }
    #endif
    

    That way, b.h won't declare foo() unless a.h was included before.

    I should look at those files to say for sure, but probably it's something like this.