Jan 21, 2013 at 3:45pm UTC
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;
}
}
Jan 21, 2013 at 3:46pm UTC
I think you have not defined the int factorial(int); function.
HTH,
Aceix.
Jan 21, 2013 at 4:39pm UTC
What code is in file factorial.h ?
Last edited on Jan 21, 2013 at 4:40pm UTC
Jan 22, 2013 at 12:21am UTC
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 Jan 22, 2013 at 12:40am UTC
Jan 22, 2013 at 1:27am UTC
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 Jan 22, 2013 at 1:28am UTC
Jan 22, 2013 at 1:42am UTC
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.