开发者

Using variables globally throughout all files set up in a header file

开发者 https://www.devze.com 2023-02-06 06:51 出处:网络
Hey everyone! I\'ve recently started using header files in my c++ programs (fairly new to it) and was wondering what the best way to initialize global variables across all your files.

Hey everyone!

I've recently started using header files in my c++ programs (fairly new to it) and was wondering what the best way to initialize global variables across all your files.

I currently have a header file outlining a program class with: init(), render(), loop(), event()... (etc) Each of these is set up within their own own file, init.cpp etc..

So whats the best way to initialize variables so that all of the files can use them? Should I do it in the header file? Or is that a bad way to go about it.

Thanks in advance!

-Devan

Edit with organization info, didn't want to do it in the comments because there are no code blocks.

Here is my header file (CGame.h)

class CGame
{
public:  
    CGame();  
    int execute();
    bool init();
    void event();
    void loop();
    void render();
    void cleanUp();
protected:

private:
bool running;

}

And then each of those methods is defined within their own .cpp file

#include "CGame.h"
void CGame::render() 
{
}

Then all of them are called upon within my main.cpp

CGame::CGame()
{
    running = true;
}

int CGame::execute()
{
    if(init() == false)
    {
        return -1;
    }

    开发者_如何学JAVAwhile(running)
    {
        loop();
        render();
    }
        cleanUp();
        return 0;
}

int main (void)
{
    CGame app;
    return app.execute();
}

Is this not the correct way to do it? I think I read it in an old SDL tutorial.


Do not use global variables.

Until you have learned to do without global variables, declare the variables as extern in the header file, e.g extern int pi. This tells the compiler: "An integer named pi exists, don't care where it is, the linker will know where to find it". That way you can initialize them anywhere you want.

The best location is a matter of personal taste. Basically either use a central c++-file for all the variables or put them into the c++-file that they most closely relate to. Especially if the variable is used in only one source file, do not put it in the header but declare and define it in that source file.

0

精彩评论

暂无评论...
验证码 换一张
取 消