Changing/Using a variable that is in a differnet source file

Started by
3 comments, last by rip-off 13 years, 11 months ago
Hi guys, Say for example, I have a source file names a.cpp with my main function and all. In this file I have a global integer named a. How can I use/change this global variable a in a function that I have in another file, for example b.cpp. They are both compiled into one later on. Is this even possible? I think I might have to look into what the extern keyword actually does. Cheers, Brick
Fate fell short this time your smile fades in the summer.
Advertisement
in a.cpp you might have:

int global = 10;

in b.cpp you would then have

extern int global;

You can then access global in either file (same variable).

Interested in Fractals? Check out my App, Fractal Scout, free on the Google Play store.

Oh ok, so the extern keyword basically states that the variable I'm using is defined elsewhere (externally)? Does this also work for functions? If I wanted to store a pointer to a function, which has it's prototype and definition in a.cpp, in a variable in b.cpp? I know I should use a header file for this, but I'm just curious.
Fate fell short this time your smile fades in the summer.
For a function you need only add its prototype, IE:

in a.cpp you might have:

int function(){  return 10;}

in b.cpp you would then have

int function();


However, if you plan on calling the function across many source files, you better place the prototype in a header and include that header in any sources using the function.

A function pointer is really a variable so you would use extern.
Functions are implicitly "extern". You can use "static" to make them local to a particular translation unit, or place them in an anonymous namespace.

In general though, you should avoid global variables. They don't scale past very small programs. Try see if you can write your program in terms of parameters and return values rather than global state.

This topic is closed to new replies.

Advertisement