ruthless
ruthless

Reputation: 1140

Undefined reference to randomInteger

I am having a problem when I am trying to include an use a function from a header that I created. Below is my header file: random.h

#ifndef _random_h
#define _random_h

int randomInteger(int low, int high);

#endif // _random_h

Next is my implementation file: random.cpp

#include <iostream>
#include "random.h"
using namespace std;

int randomInteger(int low, int high)
{
    return 1200;
}

Now this is my main program below: helloworld.cpp

#include <iostream>
#include "random.h"


int main()
{
    int num = randomInteger(10, 110);
    std::cout << num << std::endl;
    return 0;

}

I am getting an error when I run my main program which says undefined reference to randomInteger(int, int).

Upvotes: 0

Views: 215

Answers (1)

Salgar
Salgar

Reputation: 7775

You need to compile random.cpp and helloworld.cpp with the -c flag (assuming gcc/g++), for compile only. As this will just create you an object file, and won't look for a specific main function()

Then you need to compile with something like this g++ -o myprogramtorun random.o helloworld.o

OR you can do it in one step like this:

g++ -o myprogramtorun random.cpp helloworld.cpp but this becomes unsustainable

Upvotes: 1

Related Questions