Sharing runtime variables between files

Posted by nightcracker on Stack Overflow See other posts from Stack Overflow or by nightcracker
Published on 2011-03-16T16:04:35Z Indexed on 2011/03/16 16:10 UTC
Read the original article Hit count: 253

Filed under:
|
|

I have a project with a few files that all include the header global.hpp. Those files want to share and update information that is relevant for the whole program during runtime (that data is gathered progressively during the program runs but the fields of data are known at compile-time). Now my idea was to use a struct like this:

global.hpp

#include <string>

#ifndef _GLOBAL_SESSION_STRUCT
#define _GLOBAL_SESSION_STRUCT

struct session_struct {
    std::string username;
    std::string password;
    std::string hostname;
    unsigned short port;
    // more data fields as needed
};

#endif

extern struct session_struct session;

main.cpp

#include "global.hpp"

struct session_struct session;

int main(int argc, char* argv[]) {
    session.username = "user";
    session.password = "secret";
    session.hostname = "example.com";
    session.port = 80;

    // other stuff, etc

    return 0;
}

Now every file that includes global.hpp can just read & write the fields of the session struct and easily share information.

Is this the correct way to do this?

NOTE: For this specific project no threading is used. But please (for future projects and other people reading) clarify in your answer how this (or your proposed) solution works when threaded. Also, for this example/project session variables are shared. But this should also apply to any other form of shared variables.

© Stack Overflow or respective owner

Related posts about c++

Related posts about scope