Linking 2 cpp files

-1

enter image description here

I am supposed to call the function randint to my main function but for some reason it doesn't work. I have 3 files: randint.cpp, randint.h, and main.cpp. And I am supposed to call the function from randint.cpp. I am not sure if I am supposed to just declare the function in the header file and and write the definition in the cpp file.

main.cpp

#include "std_lab_facilities_5.h"
#include "randint.cpp"
#include "randint.h"
int main()
try {

    int x = randint();
    cout << x;

    return 0;
}


catch (exception& e) {
    cerr << "error: " <<e.what() << '\n';
    return 1;
    }
    catch (...) {
        cerr << "Oops: unknown exception!\n";
        return 2;
    }

randint.cpp

#include "randint.h"
#include <chrono>
using namespace std::chrono;

//linear congruential pseudorandom number generator

int randint() {
    //use the clock for an initial pseudorandom number
    static long x = time_point_cast<microseconds>(system_clock::now()).time_since_epoch().count();
    //calculate the next pseudorandom number
    // parameters from glibc(?)
    x = (((1103515245L * int (x)) & 0x7fffffff) + 12345)& 0x7fffffff;
    return x;
}

randint.h

int randint();
c++
asked on Stack Overflow Oct 3, 2017 by Papes Traore • edited Oct 3, 2017 by Papes Traore

1 Answer

-2

In the .H file inside the class you want

public:
int randint();

and in the .CPP that you want to call the function you need:

        randint randint; //<--- Telling the class in this case main that randint exists(second randint can be whatever name you prefer)

       randint.randint(); //<--- Here you call the function

I would also recommend you to use the class wizard when creating new files.

answered on Stack Overflow Oct 3, 2017 by Koranen

User contributions licensed under CC BY-SA 3.0