Sign in to follow this  
BrickInTheWall

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

Recommended Posts

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

Share this post


Link to post
Share on other sites
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).

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this