I declare then instantiate a static variable in a DLL.
// DLL.h
class A
{
//...
};
static A* a;
// DLL.cpp
A* a = new A;
So far, so good... I was suggested to use extern rather than static.
extern A* a; // in DLL.h
No problem with that but the extern variable must be declared somewhere. I got Invalid storage class member.
In other words, what I was used to do is to declare a variable in a source file like this:
// In src.cpp
A a;
then extern declare it in another source file in the same project:
// In src2.cpp
extern A a;
so it is the same object a at link time. Maybe it is not the right thing to do?
So, where to declare the variable that is now extern?
Note that I used static declaration in order to see the variable instantiated as soon as the dll is loaded.
Note that the current use of static works most of the time but I think I observe a delay or something like this in the variable instantiation while it should always be instantiated at load time. I'm investigating this problem for a week now and I can't find no solution.
Related
Considering the example below:
header.h
extern int somevariable;
void somefunction();
source.cpp
#include "header.h"
somevariable = 0; // this declaration has no storage class or type specifier
void somefunction(){
somevariable = 0; // works fine
}
I couldn't find the answer to the following questions:
Why can't I just forward declare int somevariable and initialize it in the .cpp file?
Why is the somefunction() function able to "see" somevariable when declared using extern int somevariable, and why is it not accessible outside of a function?
extern int somevariable;
means definition of somevariable is located somewhere else. It is not forward declaration. Forward declaration is used in context of classes and structs.
somevariable = 0;
is invalid since this is assignment and you can't run arbitrary code in global scope.
It should be:
int somevariable = 0;
and this means define (instantiate) global variable somevariable in this translation unit and initialize it to 0.
Without this statement linking of your program will fail with error something like: undefined reference to 'somevariable' referenced by ... .
Use of global variable in any langue is considered as bad practice, sine as project grows global variable makes code impossible to maintain and bug-prone.
Isn't the extern keyword supposed to simply 'blind' the compiler? Here are the codes that i can't understand why it is without an error.
struct A {
int a;
};
class B {
static A x;
public:
void f() { x.a=0; }
};
extern A B::x; // not allocated.
main() {
B z;
z.f();
}
As you already know, the static member should be instantiated manually. However, i added the extern keyword, which means it's not actually allocated. It is very weird that it compiles fine!
There is no such thing as an extern declaration for static member variables! The variable is declared extern anyway based on the definition of the class. gcc warns that you can't explicitly declare a static member variable to be extern. However, both gcc and clang compile and link the code without further ado, clearly ignoring the extern.
Of course, with the above code it is also clear that you are compiling with some non-standard mode in the first place as main() relies on the implicit int rule which was never part of C++.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is external linkage and internal linkage in C++
Actually I want to know the importance of extern.
First I wrote some code :
file1.h
extern int i;
file2.c
#include<stdio.h>
#include "file1.h"
int i=20;
int main()
{
printf("%d",i);
return 0;
}
Now my question is that: what is the use of extern variable when I have to define the i in file2.c, declaring in file1.h is in which way useful to me .
sudhanshu
extern allows you to declare a variable (notify the compiler of its existence) without defining it (bringing it into existence). The general rule is that you can declare things as many times as you want, but you can only define them once.
This is useful if, for example, it will be defined elsewhere.
Consider:
file1.c: file2.c:
extern int xyzzy; int xyzzy;
void fn (void) {
xyzzy = 42;
}
When you link together those two functions, there will be one xyzzy, the one defined in file2.c, and that's the one that fn will change.
Now that happens even without the extern. What the extern does is to declare that xyzzy exists to file1.c so that you don't get any I don't know what the blazes "xyzzy" is errors.
In your particular case (if those are your only two files), you don't need it. It's only needed if you had another file that #included file1.h and tried to access i.
It's useful when you have three files:
foo.h
extern int i;
void bar();
a.c:
#include "foo.h"
int i = 6;
int main(){
bar();
}
b.c:
#include "foo.h"
void bar(){
printf("%d\n", i);
}
As you can see, i is shared between both a.c and b.c, not redefined per-file, as would happen without the extern keyword.
The "extern" declaration in C is to indicate that there is an existence of, and the type of, a global variable.
In C mostly each .c file behaves like a seperate module. Hence a variable with "extern" is something that is defined externally to the current module.
It is always a better practise to define the global in one place, and then declare extern references to it in all the other places. When refering to globals provided by any shared library, this is important in order to make sure that your code is referring the correct and common instance of the variable.
From Wikipedia:
When a variable is defined, the compiler allocates memory for that
variable and possibly also initializes its contents to some value.
When a variable is declared, the compiler requires that the variable
be defined elsewhere. The declaration informs the compiler that a
variable by that name and type exists, but the compiler need not
allocate memory for it since it is allocated elsewhere.
Extern is a way to explicitly declare a variable, or to force a
declaration without a definition
If a variable is defined in file 1, in order to utilize the same
variable in another file, it must be declared. Regardless of the
number of files, this variable is only defined once, however, it must
be declared in any file outside of the one containing the definition.
If the program is in several source files, and a variable is defined
in file1 and used in file2 and file3, then extern declarations are
needed in file2 and file3 to connect the occurrences of the variable.
Having extern tells the compiler its a declaration of a variable.
In your example in file1.h imagine what would happen if you didn't specify extern keyword. It will look like there are two definitions of int i. Also, a header file can be included in many .c files. If you compile those .c files and link them, linker would see multiple definitions of the same variable.
extern keyword allows you to say to the compiler ... " Use this variable right now .. I will define and initialize it later ".. i.e " Compile it now .. I will link to its definition later".
You can extern the variable when you define it in some other file and you want to use it in the current context..
The declaration in the header allows you to access the variable from more than one source file, while still only defining it in one place.
I know one should not use global variables but I have a need for them. I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp file, that variable could not be found. So it was not really global. Isn't it so that one has to create a header file GlobalVariabels.h and include that file to any other *cpp file that uses it?
I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp File that variable could not be found. So it was not realy global.
According to the concept of scope, your variable is global. However, what you've read/understood is overly-simplified.
Possibility 1
Perhaps you forgot to declare the variable in the other translation unit (TU). Here's an example:
a.cpp
int x = 5; // declaration and definition of my global variable
b.cpp
// I want to use `x` here, too.
// But I need b.cpp to know that it exists, first:
extern int x; // declaration (not definition)
void foo() {
cout << x; // OK
}
Typically you'd place extern int x; in a header file that gets included into b.cpp, and also into any other TU that ends up needing to use x.
Possibility 2
Additionally, it's possible that the variable has internal linkage, meaning that it's not exposed across translation units. This will be the case by default if the variable is marked const ([C++11: 3.5/3]):
a.cpp
const int x = 5; // file-`static` by default, because `const`
b.cpp
extern const int x; // says there's a `x` that we can use somewhere...
void foo() {
cout << x; // ... but actually there isn't. So, linker error.
}
You could fix this by applying extern to the definition, too:
a.cpp
extern const int x = 5;
This whole malarky is roughly equivalent to the mess you go through making functions visible/usable across TU boundaries, but with some differences in how you go about it.
You declare the variable as extern in a common header:
//globals.h
extern int x;
And define it in an implementation file.
//globals.cpp
int x = 1337;
You can then include the header everywhere you need access to it.
I suggest you also wrap the variable inside a namespace.
In addition to other answers here, if the value is an integral constant, a public enum in a class or struct will work. A variable - constant or otherwise - at the root of a namespace is another option, or a static public member of a class or struct is a third option.
MyClass::eSomeConst (enum)
MyNamespace::nSomeValue
MyStruct::nSomeValue (static)
Declare extern int x; in file.h.
And define int x; only in one cpp file.cpp.
Not sure if this is correct in any sense but this seems to work for me.
someHeader.h
inline int someVar;
I don't have linking/multiple definition issues and it "just works"... ;- )
It's quite handy for "quick" tests... Try to avoid global vars tho, because every says so... ;- )
In the header I declared
#ifndef SOUND_CORE
#define SOUND_CORE
static SoundEngine soundEngine;
...
but the constructor for SoundEngine gets called multiple times, how is it possible, when it's declared as global static
I call it as
#include "SoundCore.h"
and use it directly
soundEngine.foo()
thank you
I would use extern instead of static. That's what extern is for.
In the header:
extern SoundEngine soundEngine;
In an accompanying source file:
SoundEngine soundEngine;
This will create one translation unit with the instance, and including the header will allow you to use it everywhere in your code.
// A.cpp
#include <iostream>
// other includes here
...
extern int hours; // this is declared globally in B.cpp
int foo()
{
hours = 1;
}
// B.cpp
#include <iostream>
// other includes here
...
int hours; // here we declare the object WITHOUT extern
extern void foo(); // extern is optional on this line
int main()
{
foo();
}
A copy of static variables declared in header files gets created for each translation unit where you include the header.
Never declare your static variables inside header files.
You could use a singleton object.
As others mentioned in the answers, static variable in header file gets included in every file where the the header is included. If you want to still keep it static and avoid multiple instantiations then wrap it in a struct.
//SoundCore.h
struct Wrap {
static SoundEngine soundEngine;
};
Now define this variable in one of the .cpp files.
//SoundCore.cpp
SoundEngine Wrap::soundEngine;
And use it simply as,
Wrap::soundEngine.foo();
If you include this header file in multiple files, your class will be instantiated for every inclusion. I think you better take a look at Singleton pattern, to get only 1 instance, i.e., just one constructor call.
As many other reserved words, static is a modifier that has different meanings according with the context.
In this case, you are creating an object of the class SoundEngine which is private in this module. This means that it is not visible from other modules.
However, you put this line in the header, so it is a private object in various modules. I guess that's the reason of the constructor being called multiple times.