Lots of LNK2005 errors - c++

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.

Related

Declaring a function using #define

I came across a c++ code where a function was defined in the header section of the file as follows
#define APPEND_VALUE(X, Y, I)\
{\
int idx = (Y*100+X);\
int idxn = idx + ValueCount[idx];\
TempVector[idxn] = I;\
CountVector[idx] += 1;\
}
(Note that this is not all the code and TempVector and CountVector was defined elsewhere)
Later in the code APPEND_VALUE was used like any other function. I was wondering what is the difference between the above (#define APPEND_VALUE) code and the below code
void APPEND_VALUE(int X, int Y, int I)
{
int idx = (Y*100+X);
int idxn = idx + ValueCount[idx];
TempVector[idxn] = I;
CountVector[idx] += 1;
}
What is the advantage of using one over the other? also is there a technical name for defining a function as show in the first code(the one using #define).
#define is part of something called the "preprocessor." Essentially, this is the code that is processed before the C document is compiled. Most of the preprocessor code is in a file with a ".h" extension (which is why you may have seen that when importing libraries).
The preprocessor language is primitive. For example, if it performs a "textual substitution [with] missing parentheses", the result of the preprocessor function may not be what you intended it to return (credit: #Deduplicator). Take a look at this post for an example: #define Square(x) (x*(x)). For this reason, and many others, I would prefer coding it in the regular C language when possible (just note there are many cases where the preprocessor may be faster and more helpful). Hope this helps!

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 ++: Cannot I assign values to a variable in header file?

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.

Why #define is bad? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When are C++ macros beneficial?
Why is #define bad and what is the proper substitute?
Someone has told me that #define is bad. Well, I honestly don't not understand why its bad. If its bad, then what other way can I do this then?
#include <iostream>
#define stop() cin.ignore(numeric_limits<streamsize>::max(), '\n');
#define is not inherently bad. However, there are usually better ways of doing what you want. Consider an inline function:
inline void stop() {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
(Really, you don't even need inline for a function like that. Just a plain ordinary function would work just fine.)
It's bad because it's indiscriminate. Anywhere you have stop() in your code will get replaced.
The way you solve it is by putting that code into its own method.
In C++, using #define is not forcibly bad, although alternatives should be preferred. There are some context, such as include guards in which there is no other portable/standard alternative.
It should be avoided because the C preprocessor operates (as the name suggests) before the compiler. It performs simple textual replacement, without regard to other definitions. This means the result input to the compiler sometimes doesn't make sense. Consider:
// in some header file.
#define FOO 5
// in some source file.
int main ()
{
// pre-compiles to: "int 5 = 2;"
// the compiler will vomit a weird compiler error.
int FOO = 2;
}
This example may seem trivial, but real examples exist. Some Windows SDK headers define:
#define min(a,b) ((a<b)?(a):(b))
And then code like:
#include <Windows.h>
#include <algorithm>
int main ()
{
// pre-compiles to: "int i = std::((1<2)?(1):(2));"
// the compiler will vomit a weird compiler error.
int i = std::min(1, 2);
}
When there are alternatives, use them. In the posted example, you can easily write:
void stop() {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
For constants, use real C++ constants:
// instead of
#define FOO 5
// prefer
static const int FOO = 5;
This will guarantee that your compiler sees the same thing you do and benefit you with name overrides in nested scopes (a local FOO variable will override the meaning of global FOO) as expected.
It's not necessarily bad, it's just that most things people have used it for in the past can be done in a much better way.
For example, that snippet you provide (and other code macros) could be an inline function, something like (untested):
static inline void stop (void) {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
In addition, there are all the other things that code macros force you to do "macro gymnastics" for, such as if you wanted to call the very badly written:
#define f(x) x * x * x + x
with:
int y = f (a + 1); // a + 1 * a + 1 * a + 1 + a + 1 (4a+2, not a^3+a)
int z = f (a++); // a++ * a++ * a++ + a++
The first of those will totally surprise you with its results due to the precedence of operators, and the second will give you undefined behaviour. Inline functions do not suffer these problems.
The other major thing that macros are used for is for providing enumerated values such as:
#define ERR_OK 0
#define ERR_ARG 1
: :
#define ERR_MEM 99
and these are better done with enumerations.
The main problem with macros is that the substitution is done early in the translation phase, and information is often lost because of this. For example, a debugger generally doesn't know about ERR_ARG since it would have been substituted long before the part of the translation process that creates debugging information.
But, having maligned them enough, they're still useful for defining simple variables which can be used for conditional compilation. That's pretty much all I use them for in C++ nowadays.
#define by itself is not bad, but it does have some bad properties to it. I'll list a few things that I know of:
"Functions" do not act as expected.
The following code seems reasonable:
#define getmax(a,b) (a > b ? a : b)
...but what happens if I call it as such?:
int a = 5;
int b = 2;
int c = getmax(++a,b); // c equals 7.
No, that is not a typo. c will be equal to 7. If you don't believe me, try it. That alone should be enough to scare you.
The preprocessor is inherently global
Whenever you use a #define to define a function (such as stop()), it acts across ALL included files after being discovered.
What this means is that you can actually change libraries that you did not write. As long as they use the function stop() in the header file, you could change the behavior of code you didn't write and didn't modify.
Debugging is more difficult.
The preprocessor does symbolic replacement before the code ever makes it to the compiler. Thus if you have the following code:
#define NUM_CUSTOMERS 10
#define PRICE_PER_CUSTOMER 1.10
...
double something = NUM_CUSTOMERS * PRICE_PER_CUSTOMER;
if there is an error on that line, then you will NOT see the convenient variable names in the error message, but rather will see something like this:
double something = 10 * 1.10;
So that makes it more difficult to find things in code. In this example, it doesn't seem that bad, but if you really get into the habit of doing it, then you can run into some real headaches.

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.