I'm developping a Blackberry 10 mobile app. using the momentics IDE (BB Native SDK).
In my application, I want to use global variables that will be shared by many classes.
I tried the code below like described in this link, but when I add the extern instruction before the declaration of the variable "g_nValue* " in the ".h" file, it returns the error "storage class specified for 'g_nValue'"
*/ global.cpp:
// declaration of g_nValue
int g_nValue = 5;
*/ global.h:
#ifndef GLOBAL_H // header guards
#define GLOBAL_H
// extern tells the compiler this variable is declared elsewhere
extern int g_nValue;
#endif
Any one have an idea on this? I searched a lot and they all said that the extern instruction should not cause any trouble.
An alternative to extern are static variables inside a class:
//.h
struct Globals
{
static int g_global_var;
};
//.cpp
int Globals::g_global_var = 0;
//usage:
Globals::g_global_var;
the extern qualifier only tells the compiler, "this symbol is defined in a different source file" - so the symbol exists, it's safe to use it. You will get a linking error if you actually "lie" about it and don't define the symbol - but that's a different story.
There does not seam to be any problem with the code you showed us.
But here is a link which might help you get a better idea...
You don't declare the variable exteren in the compilation unit it's defined in. You only declare it extern (and don't define it) if you want to use it in other .cpp files (compilation units).
Your code seems fine. Maybe the you have an error elsewhere. Maybe there is a semicolon (;) missing in a line before extern int g_nValue.
Related
There are other questions about using extern and const in C++. I also have read about internal and external linkage (it is been a while since I used C++) But I would appreciate if someone reminds to me about the usage of the following particular situation.
I have two cpp files: Description.cpp and Register.cpp and one hpp file: Description. h .They are something like this
//Description.cpp
#include "Description.hpp"
extern const FD models[];
//some other code
.
//Register.cpp
#include "Description.hpp"
extern const FD models[2]={
{"elementA",{1,2}},
{"elementB",{3,4}}
};
.
//Description.hpp
struct FD{
string name;
double v[2];
};
I am wondering why the extern keyword is necessary in Register.cpp
As discussed in the comments, by default, a const object has internal linkage, meaning you can only see it from the file you define it in. To change that, you use the keyword extern, which means "this variable can be seen from other files". Therefore, in Register.cpp, you need extern to tell the linker to make this visible elsewhere, and in Description.cpp you need extern to tell the compiler it might be defined elsewhere.
A better solution would be to move the declaration extern const FD models[]; into a .hpp file (either Description.hpp or a new Register.hpp, depending on details of your project). Then in Description.cpp and any other code that uses models, you include that file and don't need the declaration at all. In Register.cpp, you also include this header. Then the compiler knows that models has external linkage and you don't need to say extern again.
I read over a few articles about this, and am taking a few introductory courses to C++ concurrently. All of the courses I am taking and these articles just don't help me understand how to implement the extern and static extern storage class. I don't feel comfortable moving on until I really have a grasp on this, even though what I am seeing from other programmers is that they do not use these storage classes, but use inheritance from a header file and local static storage class to use a static variable in a function. Both of those instances I can do. I figured out how to use the static storage class both within the same source file and also by inheriting the static variable from an inherited source file.
I keep getting linker and / or compiler errors.
I am using Visual Studio 2015 Community Edition with C++11, and have CodeDroid in Android with C++98.
Will someone please teach me how to use the extern and static extern storage classes without linker and compiler errors?
For example, say I had one.cpp and two.cpp. Say I have an int main() function in one.cpp. Say I want to demonstrate outputting the value of an extern int in the main() function. And, say I have a void function called extFuncExample() declared and defined in one.cpp, and also want to output its value there.
A course I am taking has extern and static extern as two different storage classes. So, if you would be so kind as to break this down to me, so I can output these values without compiler and linker errors.
Thank you so much!
one.cpp
#include <iostream>
#include "Two.cpp"
int main()
{
extern int global_int;
std::cout << "global_int = " << global_int << '\n';
return 0;
}
two.cpp
#include <iostream>
int global_int = 100;
This, I found works. I was including #include "two.cpp" in one.cpp and also using the extern storage class which was causing the issues. Removed #include "two.cpp" and it worked!
In C and C++ there is a difference between a (forwards) declaration and a definition of symbols. extern is used to forwards declare the existence of a symbol which is external to the translation unit, that is: to 'import' symbol from "somewhere" and "make it visible" to the code being compiled. At link time the references to external symbols are resolved.
Effectively extern is a way to instruct the compiler/toolchain that it should not expect to find the symbol definition among the code being compiled, but instead should look in the libraries being linked against to find it. The linker will not bother to do so for symbols that aren't declared extern.
Apart from that, there is a somewhat common mistake that people make with extern: to use it to declare a global variable and also define it inside a header. For example:
// some header.h
extern int my_global = 40; // = 40 makes this wrong.
Then they proceed to include it multiple times in different translation units (source files):
// file1.c{pp}
#include "header.h"
// file2.c{pp}
#include "header.h"
At this point you have introduced multiple definitions for the same symbol in your program because #include simply copies the contents of the header verbatim into the context at which the #include is performed. The compiler will still compile the code, but the linker will refuse to link it because of the multiple definition error.
I am currently looking through the code written by senior engineer. The code works fine but i am trying to figure out one detail.
He uses quite a few global variables and his code is broken down into a lot of separate files. So he uses a technique to make sure that global vars are declared everywhere where he needs to access them but are only defined once.
The technique is new to me but I read few articles on the internet and got some understanding about how it works. He uses
#undef EXTERN
followed by conditional definition of EXTERN as an empty string or actual extern. There is a very good article here explaining how it works. Also there is a discussion here
What gets me confused is that all examples I saw on the web suggest to include header file in a regular way in all of the source files that need it except for one. In this single special case line that includes header is preceded by definition of a symbol that will ensure that EXTERN will be defined to an empty string and .. so on (see link above). Typically this single special case is in main or in a separate source file dedicated to the declaration of global variables.
However in the code that I am looking at this special case is always in the source file that corresponds the header. Here is the minimal example:
"peripheral1.h" :
#undef EXTERN
#ifndef PERIPHERAL_1_CPP
#define EXTERN extern
#else
#define EXTERN
#endif
EXTERN void function1(void);
"peripheral1.cpp" :
#define PERIPHERAL_1_CPP
#include "peripheral1.h"
function1()
{
//function code code here
}
Everywhere else in the code he just does
#include "peripheral1.h"
My question is how and why does that work? In other words, how does compiler know where to define and where to just declare function (or variable, or class ...)? And why is it ok in above example to have the lines :
#define PERIPHERAL_1_CPP
#include "peripheral1.h"
in actual peripheral1.cpp rather then in main.cpp or elsewhere?
Or am I missing something obvious here?
All the source files, except "perripheral1.cpp", after preprocessing contain a sequence
of external variable declarations like:
extern int a;
extern int b;
extern int c;
In peripheral1.cpp only, after preprocessing, there will be a sequence of declarations:
int a;
int b;
int c;
int d;
which are tentative definitions of the corresponding variables, which, under normal circumstances are equivalent of the external definitions :
int a = 0;
int b = 0;
int c = 0;
int d = 0;
End result is, variable are declared everywhere, but defined only once.
PS. To be perfectly clear ...
In other words, how does compiler know where to define and where to
just declare function (or variable, or class ...)?
The compiler knows where to declare, whenever it encounters a grammatical construct, which is defined in the standard to have the semantics of a declaration.
The compiler knows where to define, whenever it encounters a grammatical construct, which is defined in the standard to have the semantics of a definition.
In other other words, the compiler does not know - you tell it explicitly what you want it to do.
Nostalgia
Ahh, this takes me back a fair way (about 20 years or so).
This is a way for C code to define global variables across multiple files: you define the variable once using a macro to ensure it is defined exactly only once, and then extern it in other C code files so you can utilise it. Nowadays it is quite superfluous in many instances, however it still has its place in legacy code, and will (most likely) still work in many modern compilers, nut it is C code not C++.
Normally the likes of #define PERIPHERAL_1_CPP is utilised to ensure uniquenesss of inclusion like a #pragma once
In my own code I would use something like:
#ifndef PERIPHERAL_1_CPP
#define PERIPHERAL_1_CPP
// my includes here
// my code here
#endif
That way you can #include the file as many times as you want all over your code, in every code file even, and you will avoid multiple definition errors. To be fair I normally do it with the .h files and have something like:
// for absolutely insane safety/paranoia
#pragma once
// normally sufficient
#ifndef PERIPHERAL_1_H
#define PERIPHERAL_1_H
// my includes here
// my code here
#endif
I have never tried it on cpp files but wil llater tonight to see if there is any benefit one way or the other:)
Give me a shout if you need any more info:)
I have a global variable in one of the cpp files, where I am assigning a value to it. Now in order to be able to use it in another cpp file, I am declaring it as extern and this file has multiple functions that use it so I am doing this globally. Now the value of this variable can be accessed in one of the functions and not in the other one. Any suggestions except using it in a header file would be good because I wasted 4 days playing with that.
Sorry, I'm ignoring the request for answers suggesting anything other than the use of header files. This is what headers are for, when you use them correctly... Read carefully:
global.h
#ifndef MY_GLOBALS_H
#define MY_GLOBALS_H
// This is a declaration of your variable, which tells the linker this value
// is found elsewhere. Anyone who wishes to use it must include global.h,
// either directly or indirectly.
extern int myglobalint;
#endif
global.cpp
#include "global.h"
// This is the definition of your variable. It can only happen in one place.
// You must include global.h so that the compiler matches it to the correct
// one, and doesn't implicitly convert it to static.
int myglobalint = 0;
user.cpp
// Anyone who uses the global value must include the appropriate header.
#include "global.h"
void SomeFunction()
{
// Now you can access the variable.
int temp = myglobalint;
}
Now, when you compile and link your project, you must:
Compile each source (.cpp) file into an object file;
Link all object files to create your executable / library / whatever.
Using the syntax I have given above, you should have neither compile nor link errors.
I have 3 cpp files that look like this
#include "Variables.h"
void AppMain() {
//Stuff...
}
They all use the same variables inside them so they have the same headers but I get stuff like this
1>OnTimer.obj : error LNK2005: "int slider" (?slider##3HA) already defined in AppMain.obj
Why is that?
Keep in mind that a #include is roughly like cutting and pasting the included file inside the source file that includes it (this is a rough analogy, but you get the point). That means if you have:
int x; // or "slider" or whatever vars are conflicting
in the header file and that header file is included by three source files in a program, then they will all have a global named x defined that will conflict.
What you want to do is define the variable as extern so that the .cpp files will all get the declaration, and then in ONE of your .cpp files give the actual definition.
in Variables.h:
extern int x;
in SomeSourceFile.cpp
int x;
Of course, I'd recommend against globals, but if you must use them this would keep them from conflicting.
This is because the compiler compiles each .cpp file separately, creating a .obj file for each one. Your header appears to have something like:
int slider;
When this is included into each of your three .cpp file, you get three copies of the int slider variable, just as if you had declared it in each .cpp file. The linker complains about this because you haven't have three different things with the same name.
What you probably want to do is change your header file to read:
extern int slider;
This tells the compiler that there is a slider variable somewhere, but possibly not here, and lets the linker figure it out. Then, in one .cpp file:
int slider;
gives the linker one actual variable to link.
Because "int slider" is already defined in another file? Check that you have header guards...
#ifndef _VARIABLES_H_
#define _VARIABLES_H_
int slider;
#endif
If it is across multiple translation units, and you do want the variables to be different (ie not global), then maybe declare them in an anonymous namespace:
namespace {
int slider;
}
If you do want them global, look to James' solution.
What is happening is that each of the variables from Variables.h are given global scope for each of the individual c files. When the linker compiles all the c files, it sees multiple variables with the same name.
If you are wanting to use variables from the header file as global variables, then you will have to use the keyword "extern" in front of all of them, and in the main file don't use the keyword extern.
main c:
int n_MyVar;
other files:
extern int n_MyVar;
You can create two files Variables.h and EVariables.h, or just declare the variables in the main.cpp file.
A much better way to do this is to create a class of Variables and pass a reference to the class.
I know that this is an old thread, but I came across this as one of the first search results from Google. I solved the problem by placing the variable static.
namespace Vert
{
static int i;
}
I tried extern and in my situation that didn't seem to solve the problem.
This linking error can also be avoided if the variables included multiple times via the "Variables.h" are declared as const.
I had this error too although I work with extern definitions. The problem was initializing the variables in the extern definitions too:
ID3D11VertexShader* g_pVertexShader = nullptr;
...
extern ID3D11VertexShader* g_pVertexShader = nullptr; // here's the problem
=> error
ID3D11VertexShader* g_pVertexShader = nullptr;
...
extern ID3D11VertexShader* g_pVertexShader; // without initializing
=> no error, problem solved