variable must be absolutely global all over sources - c++

How do we make a variable global across over all .cpp files/modules of a (will-be) single binary, which is to be compiled and linked by g++ in a line?
even if it's been defined in main and has extern in var. to be included in every .cpp
extern int a_sample_var;
tried it for more a week only to fail,
.....: undefined reference to a_sample_var .....
Any generous guru helping me out?

extern int a_sample_var;
Tells the compiler: there is a int named a_simple_var defined somewhere else (think about the keyword extern: it's abbreviation for external, meaning "somewhere else"). Just leave a placeholder there and wait for the linker to find it!
Well if you do this in every cpp file (by including a header), then everyone is crying for the definition (by providing a declaration), but with no one to provide the definition. Be aware of the wording here, definition and declaration are different stuff.
In exactly one cpp file, you shall provide a definition of a_simple_var. Just simply remove the extern:
int a_sample_var; // Initialize with 0
or
int a_sample_var = 1; // Initialize with 1.
Those two are proper definitions.

Related

C++ why we include all declarations in header files

#include <iostream>
When you do this and it becomes the source passing through the preprocessor, our file will be 5k. The compiler doesn't do all this declaration, right? (There are always some things we don't use after all)
| Is the linker or compiler preventing this?
**so when you include all declaration file in header **
improve build times.
link against code without having the source for the definitions.
avoid marking everything "inline".
compiler only see the declaration as it know definition might be somewhere , then it use all definition at the linking time.
The rule of thumb is this: Header files should contain declarations, source files should contain definitions.
Two types of Declarations:
DECLARATIONS: A declaration introduces a name into a scope. Generally speaking, a scope is either an entire .cpp file or anything in code delimited by {}, be it a function, a loop within a function, or even an arbitrarily placed block of {} within a function. A name introduced, is visible within the scope from the point at which it is declared to the end of that scope. A declarations merely tells the compiler how to use something, it does not actually create anything.
extern int y; // declares y, but does not define it. y is defined elsewhere,
// but the program can now use it since it knows what it is (an integer)
PROTOTYPES: A prototype is just another name for a declaration of a function.
double someFunction( double, int );
referred from :
http://www.cplusplus.com/articles/yAqpX9L8/
Also get more information on this site:
http://www.cplusplus.com/articles/Gw6AC542/

LNK1169 and LNK2005 Errors

In my C++ project ,when i declare a global variable in my header file,i get LNK2005(x is already defined in y.obj) and LNK1169(one or more multiply defined symbols found z.exe) errors in visual studio 2012,but when i declare the global variable with const identifier,i do not get an error.From my research in msdn i understand that it is because of project properties.But i can not fix them with properties.It is only fixed with const identifier.But i can not find any rules about it in C++.is it a new feature in C++11???
This is a declaration of a global variable:
extern int my_global;
Thie is a definition of a global variable:
int my_global;
A declaration of a global variable says "here is the name of an object". A definition says "here is the name of an object, and please allocate storage space for it".
You can have as many declarations of a global variable as you want (so that anyone in any source file can refer to that same object), but you can only have one definition, since the object can only exist in one place in memory when the program runs.
The linker is complaining that you have multiple definitions of the same object because you're putting a definition in the header file, and that header gets included in multiple source files. So when, those source files get compiled, you get multiple definitions, and the linker can't do that.
The solution is to put only a declaration in the header file, and then put the definition in exactly one source file. For example:
// MyVariables.h
extern int my_global;
// MyVariables.cpp
int my_global = 42;
The reason you're seeing different behavior with the const keyword is because the const gives global variables internal linkage, meaning they're not visible to other source files. In effect, these means that each source file that includes your header gets its own copy of the constant. This takes up a little more memory, but it's not going to be noticeable. And since it's a constant, nobody's going to notice that the different constants refer to different locations in memory.
C++11 did not change any of this behavior. These constructs all behaved the same way in previous versions of C++.

C++ accessing variables from .CPP files

I'm a little fuzzy on how variable access between .cpp files works. For instance:
main.cpp
int main()
{
int a = i;
return 0;
}
main2.cpp
int i;
This generates a compiler error on main.cpp, telling me there is no in i in existence. What difference then, does the "static" keyword do in this context? (I tried Googling for it, but most of the "static keyword" info pages talk about classes & functions)
main2.cpp
static int i;
Is it the same? Does it prevent extern int i being used to access i elsewhere? How does the use of anonymous namespaces differ in how variables are handled?
main2.cpp
namespace
{
int i;
}
To sum up:
Can variables be accessed between .cpp files? (aside from extern keyword)
How does the static keyword on a global variable affect things?
How do anonymous namespaces affect things differently?
In your first example, main2.cpp defines a global variable i, which could have been accessed by main.cpp if an extern declaration of i had appeared in that file. (Normally that extern declaration would come from a header file.) You got a compiler error because i had never been declared in main.cpp, which means the compiler assumes there is no such variable.
In your second example, main2.cpp defines a file scope variable i. File scope variables are distinct from globals, even if they happen to have the same name. If you had had an extern declaration of i in main.cpp in the second example, both files would have compiled successfully, but then you would have gotten a link error because no global variable i was defined.
If you renamed main2.cpp from the second example to main3.cpp, added an extern declaration of i to main.cpp, compiled all three and linked them all together, that would succeed; main.cpp and main2.cpp would share one variable named i, and main3.cpp would have its own entirely separate variable also named i.
This stuff is called linkage. Namespaces are almost entirely unrelated to linkage. However, the anonymous namespace is special. Defining a variable in an anonymous namespace is for all practical purposes the same as defining it with static -- it makes it a file scope variable. (If I remember correctly, there is a difference, but it only matters if you are doing complicated things with exported templates, and as exported templates are so little used that they're talking about deleting the feature from the C++ standard, you don't have to worry about it.)
The value of the anonymous namespace is that you can put a class definition inside it, and that makes all of the class's methods be file-local. (Only the class { ... } block has to be inside the namespace { ... } block to get this effect.) You can't do that any other way.
All global variables have some kind of linkage. extern linkage is required to name the same variable in different contexts between different files.
extern is the default. If you actually use extern in a variable declaration, it's treated as a reference to another file. Omit any linkage specifier to actually create the variable; this must happen in only one file.
extern int i; // i exists somewhere in some .cpp file.
int i; // ah! this is the file it exists in.
// (Although nothing special about that.)
static applied to a global (at namespace scope) makes it local to the file. You get the same effect from a private namespace, so static outside function or class scope is deprecated. Many still use it though.
The exception to the rule of static meaning file-local is in classes and inline functions. Class static members should more properly be called extern since the semantics are identical. It's ugly and confusing, but I guess Bjarne just wanted to eliminate extern as a keyword.
Inline functions can have the same definition among multiple .cpp files, so when one creates a static variable, the variable definition is shared as well.
yes, for example you can use static class variables
it makes variable local and persistent to compilation unit
anonymous namespace prevents collision between symbols. it is as if you create uniquely named namespace manually

Header Guards and LNK4006

I have a character array defined in a header
//header.h
const char* temp[] = {"JeffSter"};
The header if #defined guarded and has a #pragma once at the top. If this header is included in multiple places, I get an LNK4006 - char const * * temp already defined in blahblah.obj. So, I have a couple of questions about this
Why does this happen if I have the guards in place? I thought that they prevented the header from being read in after the first access.
Why do the numerous enums in this header not also give the LNK4006 warnings?
If I add static before the signature, I don't get the warning. What are the implications of doing it this way.
Is there a better way to do this that avoids the error, but lets me declare the array in the header. I would really hate to have a cpp file just for an array definition.
Why does this happen if I have the guards in place? I thought that they prevented the header from being read in after the first access.
Include guards make sure that a header is included only once in one file (translation unit). For multiple files including the header, you want the header to be included in each file.
By defining, as opposed to declaring variables with external linkage (global variables) in your header file, you can only include the header in once source file. If you include the header in multiple source files, there will be multiple definitions of a variable, which is not allowed in C++.
So, as you have found out, it is a bad idea to define variables in a header file for precisely the reason above.
Why do the numerous enums in this header not also give the LNK4006 warnings?
Because, they don't define "global variables", they're only declarations about types, etc. They don't reserve any storage.
If I add static before the signature, I don't get the warning. What are the implications of doing it this way.
When you make a variable static, it has static scope. The object is not visible outside of the translation unit (file) in which it is defined. So, in simple terms, if you have:
static int i;
in your header, each source file in which you include the header will get a separate int variable i, which is invisible outside of the source file. This is known as internal linkage.
Is there a better way to do this that avoids the error, but lets me declare the array in the header. I would really hate to have a cpp file just for an array definition.
If you want the array to be one object visible from all your C++ files, you should do:
extern int array[SIZE];
in your header file, and then include the header file in all the C++ source files that need the variable array. In one of the source (.cpp) files, you need to define array:
int array[SIZE];
You should include the header in the above source file as well, to allow for catching mistakes due to a difference in the header and the source file.
Basically, extern tells the compiler that "array is defined somewhere, and has the type int, and size SIZE". Then, you actually define array only once. At link stage, everything resolves nicely.
Include guards protect you from including the same header into the same file repeatedly - but not from including it in distinct files.
What happens is that the linker sees temp in more then one object file - you can solve that by making temp static or putting it into an unnamed namespace:
static const char* temp1[] = {"JeffSter"};
// or
namespace {
const char* temp2[] = {"JeffSter"};
}
Alternatively you can use one source file which defines temp and just declare it as extern in the header:
// temp.cpp:
const char* temp[] = {"JeffSter"};
// header.h:
extern const char* temp[];
Header guards have absolutely nothing to do with preventing multiple definitions in your entire program. The purpose of header guards is to prevent multiple inclusion of the same header file into the same translation unit (.cpp file). In other words, they exist to prevent multiple definitions in the same source file. And they do work as intended in your case.
The rule that governs multiple-definition issues in C++ is called One Definition Rule (ODR). ODR is defined differently for different kinds of entities. For example, types are allowed to have multiple identical definitions in the program. They can (and most always have to) be defined in every translation unit where they are used. This is why your enum definition does not result in an error.
Objects with external linkage are a completely different story. They have to be defined in one and only one translation unit. This is why your definition of temp causes an error when you include the header file into multiple translation units. Include guards can't prevent this error. Just don't define objects with external linkage in header files.
By adding static you give your object internal linkage. This will make the error disappear, since now it is perfectly OK from ODR point of view. But this will define an independent temp object in each translation unit into which your header file is included. To achieve the same effect you could also do
const char* const temp[] = { "JeffSter" };
since const objects in C++ have internal linkage by default.
This depends on whether you need an object with external linkage (i.e. one for the entire program) or an object with internal linkage (unique to each translation unit). If you need the latter, use static and/or extra const (if that works for you) as shown above.
If you need the former (external linkage), you should put a non-defining declaration into the header file
extern const char* temp[];
and move the definition into one and only one .cpp file
char* const temp[] = { "JeffSter" };
The above declaration in the header file will work for most purposes. However, it declares temp as an array of unknown size - an incomplete type. If you wish to declare it as an array of known size, you have to specify the size manually
extern const char* temp[1];
and remember to keep it in-synch between the declaration and definition.
I respectfully disagree with the advice against defining variables in headers, because I think "never" is too broad. Nevertheless, the episode that brought me to this thread offers a cautionary tale for those who dare to do so.
I landed on this page as the result of an inquiry into the cause of warning LNK4006, calling out a long established array that I just moved from the translation unit that defines my DLLMain routine into the private header that is included in most of the translation units that comprise this library. I have compiled this library hundreds of times over the last 11 years, and I had never before seen this warning.
Shortly after I read this page, I discovered the cause of the error, which was that the definition was outside the guard block that protects everything else that is defined in the module that also defines DLLMain, which is where I usually gather all the memory blocks that need external linkage. As expected, moving the table inside the guard block eliminated the warnings, leaving me with only two, related to a brand new externally linked table, to be resolved.
Takeaway: You can define variables in headers, and it's a great place to put common blocks, but mind your guards.
Hang on... you are mixing up your declarations...you did say 'char const * * temp' yet in your header file you have 'const char* temp[] = {"JeffSter"};'.
See section 6.1 of the C FAQ, under 'Section 6. Arrays and Pointers', to quote:
6.1: I had the definition char a[6] in one source file, and in
another I declared extern char *a. Why didn't it work?
A: In one source file you defined an array of characters and in the
other you declared a pointer to characters. The declaration
extern char *a simply does not match the actual definition.
The type pointer-to-type-T is not the same as array-of-type-T.
Use extern char a[].
References: ISO Sec. 6.5.4.2; CT&P Sec. 3.3 pp. 33-4, Sec. 4.5
pp. 64-5.
That is the source of the problem. Match up your declaration and definitions. Sorry if this sounds blunt, but I could not help noticing what the linker was telling you...

Is this extern harmless?

main.h
extern int array[100];
main.c
#include "main.h"
int array[100] = {0};
int main(void)
{
/* do_stuff_with_array */
}
In the main.c module, the array is defined, and declared. Does the act of also having the extern statement included in the module, cause any problems?
I have always visualized the extern statement as a command to the linker to "look elsewhere for the actual named entity. It's not in here.
What am I missing?
Thanks.
Evil.
The correct interpretation of extern is that you tell something to the compiler. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, whether you had some extern declarations or not.
To avoid exposure of names (variables, functions, ..) outside of a specific object (file), you would have to use static.
yea, it's harmless. In fact, I would say that this is a pretty standard way to do what you want.
As you know, it just means that any .c file that includes main.h will also be able to see array and access it.
Edit
In both C and C++, the presence of extern indicates that the first declaration is not a definition. Therefore, it just makes the name available in the current translation unit (anyone who includes the header) and indicates that the object referred to has external linkage - i.e. is available across all the translation units making up the program. It's not saying that the object is necessarily located in another translation unit - just that 'this line isn't the definition'.
End edit
In C, the extern is optional. Without it, the first declaration is a 'tentative definition'. If it were not for the later definition (which is unambiguously a definition because it has an initializer), this would be treated as a definition (C99 6.9.2). As it is, it's just a declaration and does not conflict.
In C++, the extern is not optional - without it, the first declaration is a definition (C++03 3.1) which conflicts with the second.
This difference is explicitly pointed out in Annex C of C++:
"Change: C++ does not have “tentative definitions” as in C
E.g., at file scope,
int i;
int i;
is valid in C, invalid in C++."
The extern is harmless and correct. You couldn't declare it in the header without extern.
As an extra, usually it is best practice to create a macro or a constant to hold the size of the array; in your code the actual size (100) appears twice in the source base. It would be cleaner to do it like this:
#define ARRAY_SIZE 100
extern int array[ARRAY_SIZE];
...
int array[ARRAY_SIZE] = { 0 };
But maybe you did not want to include this in the code snippet just for the sake of brevity, so please take no offense :)
From a compilation or execution point of view, it makes no difference.
However, it's potentially dangerous as it makes array[] available to any other file which #includes main.h, which could result in the contents of array[] being changed in another file.
So, if array[] will only ever be used in main.c, remove the line from main.h, and declare array[] as static in main.c.
If array[] will only be used in the main() function, declare it in there.
In other words, array[] should have its scope limited to the smallest possible.