Changing/Using a variable that is in a differnet source file
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
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).
int global = 10;
in b.cpp you would then have
extern int global;
You can then access global in either file (same variable).
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.
For a function you need only add its prototype, IE:
in a.cpp you might have:
in b.cpp you would then have
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.
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.
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
Popular Topics
Advertisement