Define global variable as hash - c++

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.

Related

Declare and define static variable in C++ header?

Many other questions deal with how to allocate a variable by declaring it in a header file and defining it (allocating) in a .cpp file.
What I want to do is not use any .cpp files for my class, and to define all functions as inline (in the header file). The problem that I run into is how to define static member variables so that even when the .h file is included in multiple compilation units I don't get the "first defined here" linker error.
I'm open to preprocessor hacks, etc. if it gets the job done. I just want to avoid any .cpp files.
If it matters I'm using GCC.
You can abuse the singleton pattern if you really must avoid any .cpp files:
class Foo {
public:
static Bar& getMyStatic() {
static Bar bar;
return bar;
};
};
This works because now the variable is a static variable inside a function, and static has a different meaning within a function context than within a class context. And for functions, the linker does recognize multiple identical definitions and throws away the copies.
But, of course, I would strongly advise against avoiding .cpp files: It means that you get into a situation where you have to build the entire program, or at least large parts of it, in one big piece. Every change you do will necessitate a complete rebuilt which slows down your change-compile-test cycle significantly. For very small projects that might not be a problem, but it is for medium to large ones.
With static variables you have to put in a .cpp file to avoid the possibility of multiple static variables when the intention is to have just the one. Besides it is not a good idea to have large inline methods as it is only a hint to the compiler but also makes compilation take longer (you change some of those functions in development and then lots of dependent files will need to get compiled!)
However if you do not want lots of .cpp files with just a few statics in it why not have just one file to store them in.
As long as you only include that header file once in your whole project, you'll be OK. However, that's a pretty strong requirement, and can be difficult to make others adhere to.
You could have a static variable, but that means you have more than one for the entire program, which may or may not matter (bear in mind that you can't change it in the future, so you may have what's known as a "latent bug" - you change some other code, and all of a sudden you have created a new bug, because the variable isn't ONE variable).

restricting scope of variables in headers

I have a multi-file program consisting of
main.cpp
ext1.cpp
ext2.cpp
ext3.cpp
vars.h
As the name suggests, main.cpp is the main file, extX.cpp contains various functions and vars.h some global constants.
However, in main.cpp there are also (a few!) variable declarations, but they must only be within the scope of main.cpp -- that is why I haven't placed them in vars.h
I want to reduce the amount of code in main.cpp (for clarity-issues). I am looking for a way to declare these variables inside a header of some sort, but in a way that it is only visible to main.cpp.
Is it correctly understood that if I place them all inside e.g. vars_main.h (with no external keyword) and just include "vars_main.h", then I have achieved my goal?
Is it considered to be "correct" C++-style to do it this way?
If those variables are used only in main(), then yes, you could do that. But I would not go as far as considering it a "correct C++ style".
If one day you will end up including that header file into another translation unit (maybe because you will need to share just one of those variables), the linker will start complaining about multiple definitions.
At that point, to overcome this, you could use the static keyword to give those variables internal linkage and workaround the problem of multiple definitions. This way, however, each translation unit (.cpp file) will hold its own copy of those variables, which is probably not what you want, especially if they are not constant - just for the record, global constants have internal linkage by default, so you won't need to explicitly qualify them as static.
The normal practice here is either to leave those variable definitions in main(), or to have one header which contains only extern declarations of those variables, and one translation unit that contains their definitions. Then, all the files which need to access those variable would just import the header with the declarations.
The usual practice would be to go ahead and define them in main.cpp, since they're in a distinct block and won't affect the readability of the code. However you can certainly move them out to a separate include file that's only included in one .cpp, that's a stylistic choice that's completely up to you.
If the variables you are talking about are global variables private to main, I think that you should let them in main.cpp. If they are not used anywhere else, it does not make sense to declare them in a header
You could also create a class implementing the "main" features with your variables in private scope so that they won't be used by other parts of the implementation .

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.

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.