using extern keyword to declare variables in header files / c++ - c++

What is the proper way of declaring variables in the header file in c++? And if it is not a good idea, then why? Thank you.

The correct way would be to declare the variable with the extern keyword in the header file and then you have to declare it in one (!) cpp file without the extern keyword.
But:
Variables in header files are global variables. These have much problems. Here a few:
You don't know in which order they are initialized. When one is a class and their constructor accesses another global variable, it is possible that this other global variable isn't initialized
Global variables waste your namespace
When you use global variables, you almost certainly don't use well-known and proven programming concepts (like modularity). Also your functions will have many side effects which makes your code hard to understand. In a few weeks you will no longer know, which functions will change which variables, and so on. Your code will be much more readable and understandable, if you stick to this concepts and don't use global variables.
You should never use global variables in C++. They are only there for backward compatibility with C.

Related

How to "hide" a variable inside the header file?

The header file contains two variables.
Because of the structure of my program, I have two "ld: duplicate symbol" errors.
These two variables have only local significance.
Is there any way of making these variables "private", so they wouldn't be seen outside of the header file even if the header file is included to another source file?
EDIT: please tell me, would it be nice if I will put the variables to the cpp file? These variables are very big arrays, defined while initializing, and take a lot of lines of code...
extern char Lookup[][3] = { "aa", "ab", "ac", "ad", "ae", "af", ... and so on (really long)}
The solution is to not define variables in your header file.
If you absolutely must share variables between internal source files (and I recommend that you don't), then you should do the following:
Create an "internal.h".
Declare your variable extern in that header file.
Include "internal.h" in both your internal source files.
Define the variable in one or other internal source files.
The variable is now hidden from the outside world. (It's probably still visible in your object files, but you can use platform-specific trickery to strip it.)
Do not define variable in headers.
Use extern to declare a variable in a header without defining it.
I'm always weary about variables which are "on the loose". I mean: they do affect something don't they? They "belong" to a class?
Shouldn't you just declare them under a class, and then declare them as static variables? (And given the syntax, probably constants too)? In that case you can simply use everything normally done with static variables (initializer lists, static initialize function etc). Seems to me much more clearer, as now your variable is tied with something.

Control access to C++ global scope?

I sometimes have to transform some matured c source code into classes. A problem that sometimes arises is that some functions share global variables. This typically is hard to find.
I just was thinking about, if there is a possibility to disallow a class explicitly to use symbols from the global scope or anything like that. Any ideas?
EDIT:
Of course i could search for all global varialbles and transform them to class members, but that can be somewhat difficult. If the source code has some 1000 lines i can not review all the code. I just wonder, if the compiler could help me to find them.
You can put all the global variables in a namespace scope (may be more than 1). After this the compiler will complain for the ex-global variables. Just go and fix accordingly.
Edit: For the new question, No there is no facility from compiler which will single out the global variables. Moreover, finding global variables is easy and does not require code review or restructuring. It's a mechanical job. As soon as you find it, enclose it in a namespace scope. e.g.
int g_value;
converts to,
namespace Globals {
int g_value;
};

Define global variable as hash

I have a number of C++ classes, alot of them (not all) share two "static size variables" e.g.
share.h
/*Other variables in this header used by all classes*/
static size width=10;//Used by about 60%
static size height = 12;//used by about 60%
So I placed them in a header file along with other objects that all classes share.
when I compile the project I get alot of warnings (from the classes which dont use these), which complain about them being defined and not used. But I need them there!
So I ask, is there a way to hash these to prevent such warnings?
Hashing them so that they can be defined! preventing warnings from classes calling this header file which dont require these last two variables, but they call header because they need everything else init
You should place them in an individual header file. So you can include it only in the classes they need it. This avoids the warning in the other classes. So in the end you will have two header files. One where the stuff for all classes is included and another where the variables which are not used in all are defined.
However try to avoid global variables.
Edit reading tune2fs' answer, I realized I may have interpreted the question wrong.
Perhaps you forgot to use extern in the header file? If you just include static definitions in the header file all compilation units will have unique copies, not shared. See also this explanation of static/extern
Edit Disambiguated in comments
static SomeClass NotUnusedInstance;
static void unused_vars_helper()
{
static SomeClass* take_address = &NotUnusedInstance;
}
This approach is design to have minimal impact (not invoking any actual code; take_address isn't actually initialized unless you call unused_vars_helper).
This should work pretty well for your case. You can make unused_vars_helper() static and/or move it inside an anonymous namespace to prevent external visibility of the helper.

When is it appropriate to use static (over unnamed namespaces) in C++?

I have been reading articles about unnamed namespaces the whole day, most articles explained when you should use unnamed namespaces over the static keyword. But I am still left with one big question when is it appropriate to use static? After all it is not completely deprecated, what about header files with static functions should I put them into unnamed namespaces now?
#ifndef HEADER_H
#define HEADER_H
static int func() {
...
}
// versus:
namespace {
int func() {
...
}
};
#endif // HEADER_H
Or what about static member functions?
Greetings
The precise wording of the standard is:
The use of the static keyword is deprecated when declaring objects in namespace scope.
Functions in a header file should be inline rather than static or in an unnamed namespace. inline means you will only end up with at most one copy of the function in your program, while the other methods will give you a separate copy from each file that includes the header. As well as bloat, this could give incorrect behaviour if the function contains function-static data. (EDIT: unless the function is supposed to have different definitions in different compilation units, perhaps due to different preprocessor macros that are defined before including the header file. In that case the best approach is not to include it at all, but rather to bury it in an unmarked grave with a stake through its unholy heart.)
Data objects, apart from constants, usually shouldn't be defined in header files at all, only declared extern.
Static member functions are a different kettle of fish, and you have to use static there as there is no other way to declare them. That usage isn't deprecated, since it isn't in namespace scope.
UPDATE: C++11 has removed the deprecation, so there's no longer any particular reason to prefer unnamed namespaces over static. But you still shouldn't use either in a header file unless you're doing something weird.
There is no advantage of static in namespace scope over unnamed namespaces which I know of. Use unnamed namespaces, as in the example above. Actually in the example above I can't see why is static or unnamed namespace necessary. Maybe inline?
And static member functions have nothing to do with static at namespace scope. Static member functions (and nonfunction members) are still valid.
In a header file there's usually no point in specifying internal linkage, or using an anonymous namespace.
In a separately compiled implementation file you can use static or an anonymous namespace to avoid linkage level name collisions or client code relying on implementation details. An anonymous namespace lets you have external linkage, which is required for template parameters, and it also supports class definitions. But in the end it's just a question of practicality and personal preference, on a case by case basis.
static for a member function has nothing to do with linkage specification. A static member function has external linkage anyway.
static can be preferable if you are using some tools. It also behaves a bit better with auto indent functionality in most text editors. It's a bit sad, when you have to avoid using something useful because it doesn't work with tools that should really support it, but I promise you'll get over it.
An example question that gives some hint of potential pain in the debugging department:
Viewing namespaced global variables in Visual Studio debugger?
You probably won't have to look very hard to find more problems, but the debugger issues were enough to make me entirely give up on namespaces, to the maximum extent possible, so I've never looked any further.
My personal recommendation is that for code that will be around for less than forever, one might as well go with static. Does effectively the same thing as an unnamed namespace, but, averaged out over all tools, it is better supported. In theory, one day it will disappear completely, but I'm happy to publicly admit that I'm certain that day will never actually come to pass. And in the mean time, you are saving yourself some pain.

Do you declare your module specific functions as static?

I am thinking it is a best practice to declare them as static, as it makes them invisible outside of the module.
What are your thoughts on this?
For C++, a better than static is to put it in an unnamed (anonymous) namespace. This is the preferred way to prevent pollution of the Global namespace.
namespace {
void myLocalFunction() {
// stuff
}
}
If it is truly an function which is internal only to that .c file, then yes. It should help avoid polluting the global namespace. Also, I think that the compiler is able to do some optimizations with calling conventions if the function is static since it knowns no other source file needs to know how to call it. This only really applies to c because as others have noted, c++ has namespaces to address this issue.
There was a lot about implementation details and not too much about concept.
Limiting the scope of variable/function etc.. is a good practice indeed. This is a basic concept of object oriented design - you want keep private as private. This way your interface is cleaner and code maintenance is easier. And you will not find one day that changing something that you considered as private broke compilation because somebody in another part of project liked your function and decided to use it.
In C, I make everything - functions and variables - static at file scope until I can demonstrate they're necessary outside the file. I'll make things static within a function if only that function will use them and they are not too huge. Basically, if the declaration is bigger than the rest of the function, I may put the declaration outside the function. And, of course, there's a header for the public services provided by a source file.
Agreed. As a consequence, the prototypes for the static functions must go at the top of the .c file, not in the .h file.
In C++, you should use an anonymous namespace, like so:
// foo.cpp
namespace
{
class Core { ... };
void InternalFandango(Core *);
}
void SomeGloballyVisibleFunction()
{
InternalFandango(&core);
}
Advantage: this is applicable to struct / class declarations, too.
In C, just mark the functions "static". There's nothing against using "static" in C++, too, but I've learnt to prefer the namespace, as it is one single concept that works for all declarations.
I think C and C++ have different constraints concerning static: in C you don't have namespaces and .c files are your modules, so it is really really important to put all non-public functions as static to prevent errors!
About the only potentially useful property I can think of for this use of "static" in C++, that anonymous namespaces don't provide, is that there's a warning in GCC you can switch on for unused static functions (a form of dead code). You don't get that for unused functions in anonymous namespaces, so in the unlikely event that you want the compiler to tell you when you stop using the function, do it that way.
In C code, make your functions static by default. Only make non-static functions and .h declarations for functions that will be needed by other modules.
In C++ code, put those functions that are local to the file into an anonymous namespace and make them static. In the GNU compiler at least, this will result in the best and smallest code, because no function will be written if all uses are inlined. If you intend it to be inlined, then of course marking it inline is even better than static.
I do not know why g++ writes the uncalled function bodies that are in anonymous namespaces into the output at all, but it does. Functions with hidden visibility seem to show up as well; marked as hidden symbols, but still producing unused code blocks in the object file. GCC probably doesn't understand that the code isn't needed in those cases. Or I am missing something, always possible.
If you're using GCC, then you should take a look at the visibility flag (see http://gcc.gnu.org/wiki/Visibility for a full discussion).
It'll hide symbols completely as opposed to marking them unreachable. That reduces the symbol table, and helps decrease link times.
Not only that, it opens the door for more inlining, if that's what you're after.
If by 'module' you just mean a CPP file, you could just place the declaration and the definition right in the CPP file.
In C++, you'd declare the function private like this:
class MyClass
{
public:
void publiclyAccessibleFunction();
private:
void onlyAccesibleFromWithinTheClass();
int some_member_parameter;
};
Note the onlyAccesibleFromWithinTheClass() function.