C ++: Cannot I assign values to a variable in header file? - c++

header.h
int m_linkinfo;
m_linkinfo = 1;
main.cpp
#include "header.h"
int main()
{
return 0;
}
Failed, with many errors. But if I commented the line m_linkinfo = 1;, everything is OK. Why? Cannot I assign values to a variable in header file? But If I changed the header file to the only one line: int m_linkinfo = 1;, The program is compiled successfully! Why? Is it different from the two lines of code above?

No, you can't. That's a piece of code so it needs to exist inside a function of some sort, such as:
int main () {
m_linkinfo = 1;
return 0;
}
You can, as you have seen, initialise it with:
int m_linkinfo = 1;
however, since that's allowed by the standard.
Keep in mind that it's often risky to define things in header files. By define, I mean statements that create things as opposed to those that simply notify the compiler than things exist (declaring).
That's because including the header in two different translation units can result in two copies of a thing with the same name and, if you subsequently try to link them together, you'll run into trouble.
The best way to solve that is to declare things in header files, such as:
extern int m_linkinfo;
and define them in a non-header (eg, CPP) file:
int m_linkinfo = 1;
That way, every translation unit that includes the header knows about m_linkinfo but only the CPP file creates it.

C doesn't allow code outside of functions. In your example:
int m_linkinfo;
m_linkinfo = 1;
The second line is illegal, since it isn't in a function.
Outside of functions you can only declare or define variables and functions (or give directions to the preprocessor).
However, you are allowed to initalise a variable when you define it, so you can do this:
int m_linkinfo = 1;
which is perfectly legal.

Assignment is a statement. Statements are only allowed in functions. The line in the header file is not in a function. Therefore it cannot work.

Related

How to code a library with a user defined parameter in C/C++?

Is it possible to code a library with a parameter that will be defined by the user at compile time without modifying the library?
Library:
test.h
#ifndef TEST_H
#define TEST_H
#define MAX_NB USER_DEF
void myFunc();
#endif
test.cpp
#include "test.h"
int arr[MAX_NB] = {0};
void myFunc() {
for (int i = 0: i < MAX_NB; i++ ) {
// DO SOMETHING
}
}
And the main code:
#define USER_DEF 5
#include "test.h"
void main() {
while (1) {
myFunc();
}
}
I suppose I am getting an error (USER_DEF not declared in this scope) because USER_DEF is not defined in the translation unit containing test.h and test.c, but I hope there is a way to do it, but I can't find it.
My goal is to have an array with a user-defined size (code modified).
The answer is that it doesn't make sense to use variable-sized arrays for a very restricted 8-bit system with very limited RAM.
Instead you should have a fixed size array of n bytes. Let the user pick a number, then ensure that it is less or equal to n. Then keep track of the used size with a plain integer variable. You must always reserve memory for the worst case.
The array must have static storage duration, since it will be too large to be allocated on the stack.
I'd usually go and suggest to check out the templates, although, you can create user-defined variables, they are called function parameters. Please take a look
To sum it up, this is not what you call user-defined variable, because this is defined by the programmer, not by the user of the program. This is called a constant, whatsoever. If you want to create a compile-time constant, defined by you, you can take a look at constexpr.
Also, let me explain to you why this doesn't work correctly. You guessed correctly, it's because it is not defined into the header file, but why? Because headers come first and then comes the main file. The header searches for the defined constant and fails to find it, and that is the reason why you get the USER_DEF not declared in this scope.

cpp error if trying to declare an array in another file

I wanted to make my code more clear - this is why I made an extra cpp file where I declared an array which is taking a lot of space.
But whenever I try to compile my code it says
error c2466: Assignment of an array of constant size can not be
(I translated from German, so don't wonder if you don't know this error 1by1)
The code in main.cpp (To include the file)
#include "mapOne.cpp"
And the code in mapOne.cpp:
int point[100][100][2];
point [1][0][0] = 1; [...]
Can someone help me? I hate it, if a file is >400 lines long just because there is one array declared...
You're trying to assign values to your array outside of a function, which isn't allowed. Instead, the compiler assumes you're trying to declare a new array.
Try wrapping the assignments in a function, and call that function before you start using the array.
The problem you have is happening because you didn't declare the array in an area where your function will be able to use it from. For instance, If I do the following code:
In file1.cpp
int array[20];
In file2.cpp
#include "file1.cpp"
int function1()
{
i = 1;
for (int x = 0; x<20; x++)
{
array[x] = i;
i = i + 2;
}
}
The array[x] would not be recognized. The reason it is not recognized is because even if you use the "include" code on top, you are only including the ability to use the functions that are present in the file1.cpp file. The reason you are only allowed to use the functions and not the variables is simply because the compilers don't want to mix the variables you declare in file1.cpp and file2.cpp. This makes sense because a lot of times you'll declare variables of the same name in different files because it is simpler.
What you can do however is declare the array in a header file. If your writing your function in file2.cpp, you create a header file called file2.h:
In file2.h:
class file2
{
public:
int array[20];///or whichever type of array you want to declare
}
It is important you keep the variables under the "public:" section so that all the functions you make in the file2.cpp can use it.

C++ Giving a global variable an initial value

I'm writing code in Visual C++ and I need to use a global variable. I know it's generally not a good idea, but in this case, it is necessary. I have created the variable and it is accessible from the function that needs it, but I can't figure out how to give it an initial value.
in the .h file it looks like
extern int lversion;
and in the .cpp file it looks like
int lversion;
How can I give this variable an initial value of 0?
Adding these two lines in your .h and .cpp files respectively will allow you to initialize a global variable.
.h:
extern int Val;
.cpp:
int Val = 0;
The variable does have initial value 0 as it is. Globals and statics are value-initialized unless otherwise specified. (for an int, it will be 0)
If you want any other value, you can specify it:
In the cpp file:
int lversion= 3;
or
int lversion(3);
but for a value of 0 there's no point being this verbose.

Lots of LNK2005 errors

I'm trying (or rather struggling) to create a little Blackjack game. After some JavaScript courses and a few little projects I decided to switch to C++ and found it a little bit problematic, here is my code:
http://pastebin.com/raw.php?i=4MgC1VcD
For many of you this code can be just crappy, but it makes me really happy to code, even if it doesn't work as I wanted it to :)
This is what i get:
http://i.stack.imgur.com/HpyvC.png
You need to define the method random as inline.
inline int random(int nMin, int nMax)
{
return rand() % (nMax - nMin + 1) + nMin;
}
Otherwise, each translation unit that includes the header will generate code for it.
Either this, or just declare it in the header and define it in an implementation file.
Also, declare globals as extern:
extern std::string sSuits[];
extern std::string sRanks[];
and initialize them in an implementation file.

One Method to be seen throughout the entire Project

I have a question. I have a randomnumber function that I want to be available to all my classes.
In main,
I have the function
int RandomRange(int min, int max)
{
int newValue = (rand() % max) + min;
if ( newValue > max )
newValue = max;
if ( newValue < min )
newValue = min;
return newValue;
}
But I want my classes to be able to use this function. How do I go about something like that?
Create a header:
#ifndef RANDOM_RANGE_H_INLCUDED_
#define RANDOM_RANGE_H_INLCUDED_
int RandomRange(int, int);
#endif
Then include that header in any file that needs to use the function.
When you have time, you might want to write a better implementation of the function.
Declare it as a free-standing function in a header file, and then #include it from everywhere?
The answers saying "put just a declaration in a header file" are right, but it's also worth knowing that you can avoid a separate source file for the definition, and linking the corresponding .o file, by putting this this in a header file:
inline int RandomRange(int min, int max)
{
int newValue = (rand() % max) + min;
// etc...
}
This is simpler, but means that every source file that includes the file will have to process the full definition when it's compiled, and also that every source file that includes this file will have to process <cstdlib>, which this file needs to include in order to call rand().
For such a small function and for a header as basic as <cstdlib>, it's premature optimization to worry about the effects of that on compilation time for a full build, although it will noticeably affect partial builds when this header file is changed. There are also some issues of functionality, though - if you do this then:
(a) object files that used this header file and are linked together must use identical definitions of RandomRange, so a change to the contents of the function body breaks link-compatibility. And that's identical after pre-processing - there are no macros used in this example so it's the same either way, but it's possible to make mistakes here.
(b) you can't replace the definition of RandomRange just by linking a different object file containing a different definition (for debugging, testing, or link-time application configurability).
For small functions and small projects, these drawbacks aren't normally a concern. For large functions and large projects, normally at least some of them are, which is why the standard safe thing is to have separate declarations and definitions.