multiple definition of

Hi, I'm trying to make myself a file where I declare all my functions, but it isn't going well. On my first function I get an error:
Multiple markers at this line
- first defined here
- multiple definition of `random(double)'


the code of funct.h:
1
2
3
4
5
6
#include <stdlib.h>

double random (double x)
{ //the error's at this line
	return (double) ( (rand () / RAND_MAX) * x);
}


and the main.cpp is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <windows.h>
#include "funct.h"
using namespace std;

double a, b = 15.367;

int main ()
{
	a = random (b);
	cout << a << endl;
	system ("PAUSE");
	return 0;
}


what is causing it, and how do I fix it?
Last edited on
are there any other source files in your project?
No.. only these two..
You don't have ANY other files? I'm doubtful of that.

Anyway.. try making the function inline:

inline double random(double x)

Or just put the prototype in the header and put the function body in a seperate cpp file.


Also your random function is wrong. rand() / RAND_MAX will always be zero because it's integral division. You'd need to cast to floating point to get floating point division.

return double(rand()) / RAND_MAX * x; <- better
I'm pretty much new to C++, so idk why, but a is always 0...
Would it be what Disch said?

Disch wrote:
Also your random function is wrong. rand() / RAND_MAX will always be zero because it's integral division. You'd need to cast to floating point to get floating point division.
well.. I copied the code he gave me, and it started returning only 0, so I asked. Should I use some other operator for division ?
You should seed the rand function using srand first. (Only once in your program)
srand(time(0));
well.. I copied the code he gave me, and it started returning only 0


Did you copy it wrong? It works for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <cstdlib>
#include <ctime>

double random (double x)
{
    return  double(rand ()) / RAND_MAX * x;
}

int main ()
{
    srand(time(0));

    double b = 15.367;
    double a = random (b);
    std::cout << a << std::endl;

    char c;
    std::cin >> c;

    return 0;
}
I've played around a bit, and I found out that if I put rand (); right after srand (time (0)); every next time rand (); works perfectly... ... uh.. could someone explain that
srand initializes the random number seed and is needed for rand(the random number generator) to generate a different random number. The srand command should only be used once ,(before the first rand statement is implemented) and will accomodate all subsequent occurances of rand statement in that function.

http://www.cplusplus.com/reference/clibrary/cstdlib/srand/

http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Last edited on
Topic archived. No new replies allowed.