How to initialize struct/class on the global scope

前端 未结 3 905
离开以前
离开以前 2021-01-21 05:24

I do now know how to initialize structures on the global scope.

The following is a sample code:

#include
struct A
{
    int x;
};
struct         


        
相关标签:
3条回答
  • 2021-01-21 06:04

    you are doing an assignment outside of any function. In your case you could move only one line of code to get the following:

    #include<GL/glut.h>
    struct A
    {
        int x;
    };
    struct A a;
    int main()
    {
        a.x=6;
    }
    
    0 讨论(0)
  • 2021-01-21 06:05

    The problem you are observing is not related to including glut. The compiler does not allow you to assign value to a structure in the global scope. You can achieve what you want either by calling a constructor of the structure(which would be allowed at global scope) or by calling the assignment in some function.

    EDIT: here is a somewhat related discussion: Why can't I access my array subscript in global scope

    0 讨论(0)
  • 2021-01-21 06:07

    And I am on Ubuntu 11.10, when I compile this program, I get the following errors: error: ‘a’ does not name a type

    The compiler tells you with this message, that assignments to struct members can not happen in the global scope. If you want to initialize a either write

    struct A a = {6};
    

    or using a newer syntax

    struct A a = {.x = 6};
    

    or do the initialization assignment early after program start (i.e. at the beginning of main).

    Update/EDIT:

    BTW: This has nothing to do with GLUT or any other header. This is a language specification thing.

    Update/Edit 2

    I am wondering how to pass a complex parameter to some callback function?

    Well, in the case of GLUT callbacks it's going to be difficult, because GLUT doesn't allow you to specify user defined callback data. You could use the ffcall library to create in-situ closures which are then passed to GLUT. But there's the following to consider: As soon as you hit this wall, it's time to ditch GLUT. GLUT is not a requirement for OpenGL development and was never meant as a base for complex applications. So just don't use it then.

    0 讨论(0)
提交回复
热议问题