Undefined Reference.

Can someone help a newbie solve this, I've been trying for about 2 hrs now.

obj\Debug\main.o||In function `main':|
G:\DCSTemp\Factorial Split\main.cpp|14|undefined reference to `factorial(int)'|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===|

I think something is wrong with the line: int nFactorial = factorial(nValue);
But i've reached a dead end in trying to resolve it.

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include "factorial.h"

int main()
{
for(;;)
{
int nValue = 0;
std::cout << "Enter number: ";
std::cin >> nValue;

int nFactorial = factorial(nValue);
std::cout << nValue << "factorial is " << nFactorial << std::endl;
}
}
I think you have not defined the int factorial(int); function.

HTH,
Aceix.
What code is in file factorial.h?
Last edited on
Had another attempt at this, My main code is now:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include "factorial.h"

int main()
{
for(;;)
{
int nValue = 0;
std::cout << "Enter number: ";
std::cin >> nValue;

int nFactorial = factorial(nValue);
std::cout << nValue << "factorial is " << nFactorial << std::endl;
}
}


And the Header file contain's:

#ifndef FACTORIAL_H_INCLUDED
#define FACTORIAL_H_INCLUDED

int factoril(int nTarget)
{
int nAccumulator = 1;
for (int nValue = 1; nValue <= nTarget; nValue++)
{
nAccumulator *= nValue;
}
return(nAccumulator);
}


#endif // FACTORIAL_H_INCLUDED

The error i'm getting is:

G:\DCSTemp\Factorial Split\main.cpp||In function 'int main()':|
G:\DCSTemp\Factorial Split\main.cpp|14|error: 'factorial' was not declared in this scope|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 0 seconds) ===|

Sorted, Misspelt the function in the header file.

Thank's for your replies.
Last edited on
Don't put function definitions in headers, except for template and inline.
You will have a `multiple definition' issue if several sources include that header

Put only the prototypes in the header, another source will have the definition, and you link against it.
By instance
1
2
//factorial.h
int factorial(int target);

1
2
3
4
5
6
7
//factorial.cpp
int factorial(int target){
   int accumulator=1;
   for(int K=2; K<=target; ++K)
      accumulator *= K;
   return accumulator;
}
(main.cpp as you have it)

Then you compile the sources and link them together
$ g++ -c main.cpp -o main.o
$ g++ -c factorial.cpp -o factorial.o
$ g++ factorial.o main.o -o program.bin
Last edited on
The problem is that you have a typo in the function definition.
Instead of

int factoril(int nTarget)

write

int factorial(int nTarget)

in the header.
Topic archived. No new replies allowed.